3

I am trying to get a better grip on the JS syntax and I was wondering why it is common practice in many libraries to repeat the object name after a variable with that same name has already been declared. Please see below:

var Backbone = Backbone || {};    // <= Why the duplication?

or

var listeners = this._listeners || (this._listeners = {});

UPDATE:

After further research I have found a very well written article that evaluates many Idiomatic Expressions.

The article also explains the use behind Immediately Invoked Function Expressions (IIFE), i.e the wrapping of a function within a function, like such:

(function() {
  console.log('Hello!');
})();

which is another one of those JS brainteasers that newbies like me can't quite understand.

Elmar Gasimov
  • 115
  • 1
  • 8

3 Answers3

9
var Backbone = Backbone || {};

means if Backbone is undefined or null or false, set it to {}


Longer explanation:

The assignment operator evaluates from right to left and logical operators(even though Javascript doesn't have real logical operators as they work on non-boolean operands as well) evaluate from left to right.

An expression like A || B returns B if A is undefined, null, or false.

So A = A || B either keeps A value if it already has one or assigns B to A.

fardjad
  • 20,031
  • 6
  • 53
  • 68
  • 1
    Often used in namespace buildng; http://stackoverflow.com/questions/881515/javascript-namespace-declaration – Alex K. Apr 25 '13 at 12:45
  • @fardjad Thank you so much for your answer. I will up vote your answer as soon as my rep is reaches 15. <== Done! ;) – Elmar Gasimov Apr 25 '13 at 12:56
0
var Backbone = Backbone || {};

As others have explained, this code will do the following:

  • declare a variable Backbone, check if a variable Backbone already exists within the scope,
  • if yes, assign that object (in JS everything is an object) to our declared variable (which, incidentally, has the same name)
  • if no, it will create a new empty object.

The purpose of this is modularity. Lets' say you are loading a couple of Backbone plugins, along with the bare Backbone.

  • First, you loaded the base backbone.
  • The script checks if the root scope object checks if rootscope object Backbone exists (ie. window.Backbone)
  • It does not, so we create an empty one and do stuff with it.
  • Now, the next plugin script checks if root object Backbone exists (which it does)
  • Since it does exist, it doesn't create a new empty object, but uses the existing one
  • Now it goes like this until all your plugins are loaded.

This isn't entirely correct, but something like this happens.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
-1

This is a way to default the value of the variable only if it hasn't been assigned already. You could think of it as the JS way to do optional function parameters with default values.

charlieco
  • 62
  • 2