JavaScript - Short-Circuiting



In JavaScript, short-circuiting is a feature that checks conditions and stops as soon as it knows the answer. It doesn't look for the rest of the expression, and that prevent unnecessary evaluations.

Short-Circuiting for && operator

Short circuit evaluation with &&(AND) logical operator means if the first expression evaluates to false then whole expression will be false and the rest of the expressions will not be evaluated.

Code-snippet

Below is an example snippet of short-circuiting with the && operator.

let x = 0 && "hello";  // x will be 0, as 0 is falsy and short-circuits
let y = true && "world";  // y will be "world" because the first value is truthy
let z = "hello" && "world";  // z will be "world" because both values are truthy
console.log(x);  // 0
console.log(y);  // world
console.log(z);  // world

Output

Following is the output of the above code

0
world
world

Short-Circuiting for || operator

Short circuit evaluation with ||(OR) logical operator means if the first expression evaluates to true then whole expression will be true and the rest of the expressions will not be evaluated.

Code-snippet

Below is an example snippet of short-circuiting with the || operator.

let x = 0 || "hello";  // x will be "hello" because 0 is falsy
let y = true || "world";  // y will be true because the first value is truthy
let z = "hello" || "world";  // z will be "hello" because the first value is truthy
console.log(x);  // hello
console.log(y);  // true
console.log(z);  // hello

Output

Following is the output of the above code

hello
true
hello

Short-Circuiting Assignment

Short-circuiting can be used in assignment operations as well. Means, if you have to assign something based on a condition, you can use short-circuiting.

Code-snippet

Below is an example snippet of short-circuiting in assignment operations.

let x = 0;
let y = 10;
let z = x || y;  // z will be 10 because x is falsy
console.log(z);  // 10

In above example, z will be assigned the value of y because x is falsy.

Output

Following is the output of the above code

10

Short-Circuiting in Function Calls

Short-circuiting can be used in function calls as well. Means, if you have to call a function based on a condition, you can use short-circuiting.

Code-snippet

Below is an example snippet of short-circuiting in function calls.

function greet(name) {
   return name || "Guest";
}
let x = greet("John");  // x will be "John" because name is truthy
let y = greet("");  // y will be "Guest" because name is falsy
console.log(x);  // John
console.log(y);  // Guest

In above example, if name is truthy, it will return the name, otherwise it will return "Guest".

Output

Following is the output of the above code

John
Guest
Advertisements