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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a cross-browser smooth scrolling with jQuery?jQueryWhat are CSS Specificity Rules and how does browser apply them?CSSWordPress: How to loop through ACF group fields?WordPressHow to change value of a span tag using a reference from another div using jQuery?jQueryFETCH clause in PostgreSQLPostgresHow to add a ribbon inside a container using CSS?CSS