Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object instantiation

Tags:

javascript

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.

like image 470
Josh K Avatar asked Sep 20 '10 21:09

Josh K


People also ask

What is instantiate object in JavaScript?

To instantiate is to create such an instance by, for example, defining one particular variation of an object within a class, giving it a name and locating it in some physical place.

How do you initiate an object in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

How do you instantiate a class in JavaScript?

The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.


2 Answers

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 true value. 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:

var Obj = Obj || {}; // Obj will now be {}, unless Obj was previously defined
                     //  in this scope function.... that's not very useful...

This is because after var Obj, Obj will 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 Obj has been previously declared and is now falsy:

Obj = Obj || {};     // Better make sure Obj has been previously declared.

If the above line is used when Obj has not been previously declared, there will be a runtime error, and the script will stop!

For example this Javascript will not evaluate at all:

(function() {
    Obj = Obj || "no Obj"; // error since Obj is undeclared JS cannot read from 
    alert(Obj);​            //   an undeclared variable. (declared variables CAN
})();                      //   be undefined.... for example "var Obj;" creates 
                           //   a declared but undefined variable. JS CAN try
                           //   and read a declared but undefined variable)

jsFiddle example

But this Javascript will always set Obj to "no Obj"!

var Obj ="I'm here!";
(function() {
    var Obj = Obj || "no Obj"; // Obj becomes undefined after "var Obj"...
    alert(Obj);  // Output: "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

Obj = Obj || {};

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.

  1. A variable can be undefined because it was never declared.
  2. A variable can be undefined because it was declared but has not had a value assigned to it.

A variable can be declared using the var keyword. 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 if Obj is either undeclared OR it is a previously existing variable.

like image 174
Peter Ajtai Avatar answered Sep 20 '22 00:09

Peter Ajtai


The mechanics are a bit unusual: Unlike most languages, JavaScript's || operator does not return true or false. Instead, it returns the first "truthy" value or the right-hand value. So for instance:

alert("a" || "b");              // alerts "a", because non-blank strings are "truthy"
alert(undefined || "b")         // alerts "b", because undefined is falsey
alert(undefined || false || 0); // alerts "0", because while all are falsy, 0 is rightmost

More in this blog post.

As Darin said, your var Obj = Obj || {}; is probably not a literal quote, more likely something like this:

function foo(param) {
    param = param || {};
}

...which means, "if the caller didn't give me something truthy for param, use an object."

like image 41
T.J. Crowder Avatar answered Sep 22 '22 00:09

T.J. Crowder