JavaScript OR (||) variable assignment explanation

chattsm picture chattsm · Jan 20, 2010 · Viewed 354.5k times · Source

Given this snippet of JavaScript...

var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';

var f = a || b || c || d || e;

alert(f); // 4

Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?

My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.

Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.

Answer

unwind picture unwind · Jan 20, 2010

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.