1

For example

var myVar = myVar || {};

or

var myVar = myVar || [];

What does this statement mean ?

Zaffy
  • 16,801
  • 8
  • 50
  • 77
Raheeb M
  • 505
  • 2
  • 5
  • 13

3 Answers3

2

It provides the default value for myVar in case myVar evaluates to false.

This can happen when myVar is either:

  • false
  • 0
  • empty string
  • null
  • undefined
  • NaN
soulcheck
  • 36,297
  • 6
  • 91
  • 90
0

"OR" which is used to assign a default value. An undefined value evaluates to false, hence "OR"ing it with a value returns the value, and that gets assigned to the variable.

function myNameFunction(theName)
{
   var theName = theName || "John";
   alert("Hello " + theName);
}

myNameFunction("dhruv")  // alerts "Hello dhruv"
myNameFunction()   // alerts "Hello John"
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

It's for given a default value, and the notation is called OR, as you know it from if statements etc:

Consider this scenario:

var Person = function(age){
     this.age = age;
}
console.log(new Person(20).age);
// Output will be 20.

console.log(new Person().age);
// Output will be undefined.

If you didn't give an age, the output would be undefined.

You can set a default value, if the value you want supplied doesn't exist.

var Person = function(age){
     this.age = age || 0;
}
console.log(new Person(20).age);
// Output will be 20.

console.log(new Person().age);
// Output will be 0.

To know more about when it applies, see @soulchecks answer.

André Snede
  • 9,899
  • 7
  • 43
  • 67