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
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
How to Update an Array Element in JavaScript
Learn the simplest ways to update array elements in JavaScript. This guide explains how to use assignment operators and modern methods to modify array values.
Flatten an Array One Level Deep in Javascript
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.