Welcome to my blog where I write mostly about technical things!

Destructuring Tweets – Episode 10 – Short && Circuit && Evaluation

Welcome to my blog series about demystifying JavaScript quizzes from Social Media! This time is about a rather basic concept. Let's dive right into the beautiful world of logical operators in JavaScript!

The Snippet

let name1 = " ",
  name2 = undefined,
  name3 = "ravin",
  name4 = "rav",
  username = name1 && name2 && name3 && name4;

console.log(username);

Here, we see a declaration of several variables. Or, more precisely, four names. The first one is a seemingly empty string. However, hold in mind that this is not the case! It contains a whitespace symbol. Next, they store undefined, right followed by another two strings.
The next line is where things get interesting. The previously defined variables are chained with the && operator, and the output is stored in yet another. They log this last variable, leaving us with the question of its value.

The Output

If you are unfamiliar with the presented API, the log might seem wildly random. For it is merely undefined. Isn't it weird how a logical operator does not return a bool? And why does it not take any of the provided strings into account?

The Analysis

First things first, we need to understand how the && in JavaScript works. It returns the first falsy value it encounters or the last (most right) one. Such value is one of NaN, null, 0, an empty string ("" and such), or undefined.
This definition may sound a bit weird at first. However, it makes total sense (at least in JavaScript). Please give it a thought. If everything is truthy, the last expression is returned. This final expression can also be truthy or falsy, having the sole power to determine the full statement's logical outcome.
Think through these different statements:

if ('a string' && true) {
 //?
}
if (NaN && true) {
 //?
}
if (NaN && '') {
 //?
}
if (true && false) {
 //?
}
if (true && true && false) {
 //?
}
if ('a string' && 123 && 'foo'){
 //?
}

By now, you should know why the output in the given snippet is undefined. It's merely the first falsy statement encountered! name1 is a truthy (non-empty!) string, and name 2 is a falsy undefined. The other two variables aren't even taken into consideration at this point.
Our snippet comes down to the following:

console.log(' ' && undefined); // returning undefined being falsy

This behavior is called Short-Circuit Evaluation, btw.

The logical AND expression is evaluated left to right, it is tested for possible “short-circuit” evaluation using the following rule:
(some falsy expression) && expr is short-circuit evaluated to the falsy expression;
Short circuit means that the expr part above is not evaluated,

from MDN Logical AND (&&)

Further Reading

Logical AND (&&)
MDN Expressions and Operators – Logical Operators