DEV Community

nehabharati
nehabharati

Posted on

What is short-circuit evaluation?

Introduction

We all know about the different kinds of operators in Javascript. There's arithmetic, logical, relational, unary, ternary and so on. We also know what they do and when they should be used. Here I'm going to discuss some peculiar conditions using a few of these operators to see how they behave with other data types and more importantly about short-circuit evaluation

All logical expressions evaluate from left to right. The logical operators && and || behave differently when dealing with values of different types.

&& operator

  • When the value to the left of the and operator is evaluated to false, the condition returns false
  • When the value to the left of the and operator is evaluated to true, it checks if the value to the right is true or false and accordingly provides a result.
console.log(NaN && 0)
//NaN
console.log(0 && NaN)
//0
console.log(NaN && null)
//NaN
console.log(null && NaN)
//null
console.log(1 && NaN)
//NaN
Enter fullscreen mode Exit fullscreen mode

Note: 0, -0, NaN, null, undefined and ""(empty string) are considered as false in Javascript.

|| operator

or operator works the other way around.

  • When the value to the left of the or operator evaluates to true, the operation returns true.
  • When the value to the left of the or operator is evaluated to false, it checks if the value to the right is true or false and accordingly provides a result.
console.log("" || "user")
//user
console.log(null || "user")
//user
console.log("i"||"u")
//i
Enter fullscreen mode Exit fullscreen mode

The above code shows an interesting way or works. The first value that evaluates to true is returned.
The cases seen till now are all due to short-circuit evaluation. You can read more about it here.

Relational Operators

console.log(2 < 3)
//true
console.log(10 < 2)
//false
Enter fullscreen mode Exit fullscreen mode

This is how a typical relational operator(<,>,>=,<=, etc) works.
But what if we were to compare other data types like below.

console.log("ant" < "Bat")
//false
console.log("Ant" < "Bat")
//true
Enter fullscreen mode Exit fullscreen mode

Strings are compared from left to right. The ASCII representation of strings can be found here. Lowercase letters are always greater than uppercase letters. So the code above is valid.

Summary

  • Short-circuit evaluation handles logical operation with different data types
  • and operator behaves in such a way that it returns the value which evaluates to false
  • or operator behaves in such a way that it returns the value which evaluates to true
  • Strings are compared from left to right depending on their ASCII value

That's it for this article. Hope you liked it and please leave your comments below. :)

Top comments (0)