views:

67

answers:

3

Hello,

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.

Thanks in advance for your help!

+2  A: 

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

unwind
Excellent. Thankyou kindly!
Martin Chatterton
+1  A: 

Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:

alert(null || undefined || false || 0 || 4);
Alsciende
+1  A: 

There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

Marcin
In the pretty static language C# one can use the ?? operator á la: object f = a ?? b ?? c ?? d ?? e;
herzmeister der welten