Short Circuit Conditionals With Logical OR(||) Operator - JavaScript

The main purpose of short circuiting is to stop the further execution of a program based on boolean operations.

For Logical OR(||) operator, if the true value of an expression has already been determined, than the further execution will not continue.

The second operand in an expression with logical OR will only get executed when first operand evaluates to false

Precedence for Logical OR is from left to right.

Example

Let us consider, we’ve dark mode feature on our website. If user has not selected explicitly then default mode can be set by us(developer). Same way in this website.

We can store mode value in localStorage and retrieve it back user selected mode when he/she visits again.

Example using if condition

if (!localStorage.mode) {
  localStorage.mode = "Light";
}

Example using short circuit conditional

localStorage.mode = localStorage.mode || "Light";

Now the code is just a single line to set default mode in localStorage.

If localStorage.mode is defined then it will take its value but if not defined then it will set to default value, here it’s "Light" mode.

Happy coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳