Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init object in javascript using || operator [duplicate]

Tags:

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.

like image 271
Kai Avatar asked Aug 19 '11 07:08

Kai


1 Answers

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.

like image 158
cdhowie Avatar answered Nov 03 '22 04:11

cdhowie