Init object in javascript using || operator [duplicate]

Sometimes I see in javascript code something like this:

var myObj = myObj || {};

So, what actually happen here? I suppose || operator returns true or false, but it’s not correct.

The || operator returns the left operand if it evaluates as true, otherwise it evaluates and returns the right operand. In other words, a || b is equivalent to a ? a : b except that a is only evaluated once.

To understand the || operator, let’s first look at a fairly basic example. The logical OR operator may be used to provide a default value for a defined variable as follows:

 var bar = false,  
 foobar = 5,  
 foo = bar || foobar; // foo = 5  

In this case, foo will only be assigned the value of foobar if bar is considered falsy. A falsy value could be considered being equal to 0, false, undefined, null, NaN or empty (e.g “”).

This initializes myObj unless it is already defined.

You can use this construct to get the object that is not null, undefined, etc. This is used in cases where you use myObj later on in the code which requires it to be an object. If, for some reason, myObj is undefined prior to this line, re-assigning it leaves it undefined or null, in which case it would be assigned {}.

You can think of this as:

// If the object is already defined
if (myObj)
    var myObj = myObj;
// It was undefined or null, so assign an empty object to it.
else
    var myObj = {};

|| is a short circuit operator. If the first operand evaluates to true the second is not evaluated.

Thus JS a || b is something like c# a ?? b

if myObj is undefined or null then it evaluates the expression on the right side of || which creates a new empty object

so myObj is either myObj if it is not null or an empty object if myObj is null

i hope you understand what i mean


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts