Does this produce the same results? What if function foo does not exist?
var foo = foo || function(){
console.log("I'm Batman");
}
vs
var foo = function() {
console.log("I'm Batman")
}
Does this produce the same results? What if function foo does not exist?
var foo = foo || function(){
console.log("I'm Batman");
}
vs
var foo = function() {
console.log("I'm Batman")
}
It's a way of declaring foo
if and only if it has not already been declared in some other scope. If it has, then the new, more local foo
shall be identical to the broader one.
It works because of what ||
does and because foo
is undefined
if it's not, um, defined.
The whole thing is pretty rare, though, and not one of the usual ways to declare a function.
It is known as guard operator ... one feature of javascript
x = a || b;
// if the first is true will return the first. Else will return the second;
Look more about in this question:
Hope it helps..
The code does this (more or less):
foo
was not declared in the current scope, it declares it and sets its value to undefined
. If it's already declared, it remains declared with the same value.foo
is truthy.
foo
is not changedfoo
is overwritten with the new value.Therefore
If foo
was not declared in the current scope, it is declared, and the new value is assigned.
var foo = 123; // Another scope
(function() {
var foo = foo || 'abc';
foo; // 'abc'
})();
If foo
was declared in the current scope and its value was falsy, foo
is overwritten with the new value.
var foo = ''; // Same scope, falsy value
var foo = foo || 'abc';
foo; // 'abc'
If foo
was declared in the current scope and its value was truthy, foo
is not altered.
var foo = 123; // Same scope, truthy value
var foo = foo || 'abc';
foo; // 123