-2

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")
}
David
  • 107
  • 1
  • 1
  • 12
zadubz
  • 1,281
  • 2
  • 21
  • 36

3 Answers3

5

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.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • This is wrong. If `foo` was declared in a broader scope, the local one won't be the same. See [my answer](http://stackoverflow.com/a/30020514/1529630). – Oriol May 03 '15 at 23:30
  • Then I must be misunderstanding your answer :) But understand you say that if `foo` was not declared in a local scope, but is declared in a broader one (and has a truthy value), the local value will be identical to the broader one. That won't happen. – Oriol May 04 '15 at 15:00
  • @Oriol: Oh I see: the new `foo` is in scope in its own initializer. If so then, yes, you're right: this answer is wrong. – Lightness Races in Orbit May 04 '15 at 19:48
1

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:

Javascript || operator

Hope it helps..

Community
  • 1
  • 1
0

The code does this (more or less):

  • If 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.
  • It checks if the value of foo is truthy.
    • If it's truthy, the value of foo is not changed
    • If it's falsy, foo 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
    
Oriol
  • 274,082
  • 63
  • 437
  • 513