0

This is the very first line of a JavaScript file I am modifying and and what does it do? jQuery is also used in the file.

var w = w || {};

From what I know the || is a logical operator this is a quote from the Mozilla documentation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

John Bessire
  • 561
  • 4
  • 19
  • 1
    possible duplicate of [Set a default parameter value for a JavaScript function](http://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function) – soulcheck Sep 01 '14 at 22:02
  • 2
    It checks to see if w is already defined and if not, it assigns an empty object to it. – j08691 Sep 01 '14 at 22:02
  • possible duplicate of [Is there a better way to do optional function parameters in Javascript?](http://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript) – Peter O. Sep 01 '14 at 23:15

4 Answers4

2

It sets w to w's current value if w is "truthy", and w to an empty object if w is "falsy."

Falsy values include NaN, null, undefined, 0, empty strings, and of course false.

Everything else is truthy.

Essentially, it makes sure that w is an object if it is not one already.

James Gould
  • 2,642
  • 3
  • 24
  • 48
2

It assigns w to w if it contains a value that is not false, else, it sets w as an empty object.

Chibuzo
  • 6,024
  • 3
  • 24
  • 49
2

You should see that line as a shortened version of this.

// declare w as a variable
var w;

// if w is already declared, leave it
if (!w) {
  // if not make it an empty object
  w = {};
}

In the global context (where I'm sure this is defined), using var will not overwrite an existing global.

So basically, you are ensuring that there is a var by the name of w that you are able to store properties on.

Roderick Obrist
  • 3,450
  • 1
  • 14
  • 17
0

This is to check if 'w' is truthy or falsy.

'w' is falsy if it has any of the values:

false
0
""
null
undefined
NaN

The expression (w || {}) will return 'w' if it is not a falsy value. Otherwise, it will return an empty array. So when you assign it to 'w' in the expression: var w = w || {}; It is just a way of making sure 'w' isn't a falsy value and doesn't throw any errors if it gets used later on in your code.

juliusav
  • 41
  • 1
  • 3