JavaScript Short Circuiting: What It Is and How To Use It

By | September 24, 2021

JavaScript Short circuiting is the process where the JavaScript interpreter automatically stops the execution of an expression, evaluation, or subexpression if it can tell that the value will always be the same no matter what. JavaScript short circuiting is the term given to the logic in which a sequential comparison of logical expressions can be stopped as soon as it is determined that one of the expressions is true.

JavaScript Short Circuiting Examples

JavaScript Short circuiting is a function that prevents the execution of the rest of the code if certain conditions are met. In JavaScript, it can be done with an “if” statement or with logical operators such as “&&” and “||”.

In this example, we will focus on two types of short circuiting:

  1. JavaScript short circuiting with “if” statements: This type of short circuiting is done through an “if” statement and allows you to execute code only when certain conditions are met.
  2. JavaScript Short Circuiting With Logical Operators &&

// Simple javascript 
let authorizedUser = true;

// Normal conditional statement 
if(authorizedUser) {
   showGreetings(authorizedUser);
}

// Using short-circuiting 
authorizedUser && showGreetings(authorizedUser); 

// Both will do the same
Author: CV

I am a Front-end Developer, graduate of Information Technology, and founder of w3tweaks.com. I have 12+ years commercial experience providing front-end development, producing high quality responsive websites and exceptional user experience.