Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]

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.

like image 233
chattsm Avatar asked Jan 20 '10 10:01

chattsm


People also ask

What is a logical operator JavaScript?

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.

What does the || operator do?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

Can you use || in JavaScript?

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.


1 Answers

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

like image 178
unwind Avatar answered Oct 05 '22 23:10

unwind