Javacript uses short-circuit evaluation for logical operators ||
and &&
. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true
, or false
value.
The following values are considered falsy in JavaScript.
""
(empty string)Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaN
are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello"
which makes the entire expression true, so anything further up will not be evaluated, and "Hello"
gets returned as a result of the expression. Similarly, in this case:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null
) which makes the expression false, so 2010
isn't evaluated anymore, and null
gets returned as a result of the expression.
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello"
to b
as it makes it easier to assign a default value, instead of doing if-else checks.
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messages
is falsy, and if yes, then evaluate and return noNewMessagesText
, otherwise evaluate and return newMessagesText
. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages."
.