The short circuiting was meant to stop the further execution based on boolean operations. With Logical AND(&&) operator, if the false value of expression has already been determined than further execution will not happen.
Precedence for Logical AND is from left to right.
Example
Let us consider, weโve an application on our device which uses Unsplash API to retrieve data from it. If the device is not connected to internet, then no data will not be fetched.
navigator.onLine
- We will be using
navigator.onLineproperty to verify whether the user is connected to the internet or not. - The
navigator.onLineproperty returntrueif connected to internet elsefalse.
Example using if condition
if (navigator.onLine) {
fetchUnsplashImages();
}
Example using short circuit conditional
navigator.onLine && fetchUnsplashImages();
Now the code is just a single line navigator.onLine && fetchUnsplashImages();. Here the fetchUnsplashImages() function only executes when navigator.onLine return true i.e user is connected to internet.
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.