Yogesh Chauhan's Blog

Short-Circuit Evaluation in JavaScript

in JavaScript on April 16, 2021

In this “If statement shorthand examples in JavaScript” post, I have a short example on Short-Circuit in JavaScript.

In the current post, I am just going to list few examples to understand it better rather than just theory.

&& Operator

Let’s check if a function returns true and if so, call a function. This is how we approach it conventionally.


But, we can just write this code and it will do the same thing in less code.

adult && ageValid();

The && operator will only go for the second condition if the first one is true otherwise it will stop execution after the first one.

|| Operator

Let’s check if the age of an adult is undefined then log an error. This is how we approach it conventionally.

if(adult.age === 'undefined'){
  console.log('age unknown');

We can also just log the age and it will print “undefined” like this:


But, we can just write this code and it will do the same thing in less code.

console.log(adult.age || 'age unknown' );

The || operator will check both conditions no matter the outcome of the first one.

You can check more than two conditions just like this example: a short example on Short-Circuit in JavaScript

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to apply style only to first child and/or only to children other than the first child?CSSWhere is the PHP log file located on Mac OS?PHPHow to find the HCF or GCD and LCM of two given numbers using Swift?SwiftWhat is Hadoop and Hadoop Ecosystem?MiscellaneousWhat is XP (Extreme Programming) and When should it be used?MiscellaneousHow to create a Bootstrap style accordion using CSS and JavaScript?CSS