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.


if(adult){
  ageValid();
}

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:


console.log(adult.age);
//undefined

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

amazon

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 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
Introduction to components and templates Part 2: Templates and viewsAngularMicroservices vs Monolithic ArchitectureMiscellaneousHow to use PHPMailer to send an Email via Gmail SMTP Server?PHPHow to list all PHP variables to debug the script?PHPHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScriptHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQL