Sometimes I’ll see code like this:
var Obj = Obj || {};
What does this do? I have had success writing
array = array || [];
To instantiate an array if it hasn’t already been instantiated, however I would like to know a bit more about the mechanics of this.
The technique tries to make use of something called short circuit evaluation… but it’s tricky in Javascript, and turns out to be quite dangerous if you try to make use of it for Object instantiation.
The theory behind short circuit evaluation is that an OR statement is only evaluated up to the first
truevalue. So the second half of an OR statement is not evaluated if the first half is true. This applies to Javascript……But, the peculiarities of Javascript, in particular how undeclared variables are handled, make this a technique that has to be used with great care to instantiate objects.
The following code creates an empty object except if Obj was previously declared in the same scope:
This is because after
var Obj,Objwill be undefined unless it was declared in the same scope (including being declared as a parameter to the function, if any)…. so{}will be evaluated. (Link to an explanation of var provided in the comments by T.J. Crowder).The following code creates an empty object only if
Objhas been previously declared and is now falsy:If the above line is used when
Objhas not been previously declared, there will be a runtime error, and the script will stop!For example this Javascript will not evaluate at all:
jsFiddle example
But this Javascript will always set
Objto “no Obj”!jsFiddle example
So using this type of short circuit evaluation in Javascript is dangerous, since you can usually only use it in the form
Which will fail precisely when you would most want it to work… in the case where Obj is undeclared.
Note: I mention this in the comments of the penultimate example, but it’s important to understand the 2 reasons that a variable can be undefined in Javascript.
A variable can be declared using the
varkeyword. Assigning a value to an undeclared variable creates the variable.Trying to use an undefined variable that is also undeclared causes a runtime error. Using an undefined variable that has been declared is perfectly legal. This difference is what makes using
Obj = Obj || {};so tricky, since there is no meaningful form of the previous statement ifObjis either undeclared OR it is a previously existing variable.