For example
var myVar = myVar || {};
or
var myVar = myVar || [];
What does this statement mean ?
For example
var myVar = myVar || {};
or
var myVar = myVar || [];
What does this statement mean ?
It provides the default value for myVar
in case myVar
evaluates to false.
This can happen when myVar
is either:
"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"
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.