Search code examples
javascriptvariable-assignmentshort-circuiting

JavaScript Short-Circuit Variable Assignment with Commas


I am reviewing some code for a JavaScript widget that I downloaded and there is a variable assignment similar to the following:

var a = a.something || a.somethingElse, c, d, e, f, g;

What I am wondering is if this is equivalent to this:

var a = a.something || a.somethingElse;
var c, d, e, f, g;

or this:

var a = a.something || a.somethingElse || c || d || e || f || g;

I have been reading up on short-circuit evaluation and assignments, and I understand that the first part is saying:

if ( a.something != (null or 0 or false)) {
    a = a.something;
} else {
    a = a.somethingElse;
}

but I cannot seem to find any resources that use an example like this one.


Thanks, for your help!


Solution

  • Your understanding is correct. A comma seperated list in a var statement is treated like individual Ines.

    As for the boolean OR statement: If the first expression is falsy, the second will be used. You can add more, as in your third example.