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.
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.
Summary. Because JavaScript is a loosely typed language, the operands of && and || can be of any type. The concepts of falsy and truthy are handy to deal with types conversion within logical operators.
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With