YogeshChauhan . com

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

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

WordPress get_posts ExamplesWordPressCSS backface-visibility PropertyCSSLearn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHPA complete guide to add responsive YouTube videos using HTML and CSSCSSSteps to Secure a VPNMiscHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQL