Javascript Tips: Short-Circuit Evaluation

Javascript Tips: Short-Circuit Evaluation

This is going to be a short tip, but I hope It would be helpful when you are working with conditional statements.

In Javascript, logical expressions are evaluated from left to right, in a way that we can create short-circuit evaluation, which means only the first part of the expression is evaluated, no matter the content from the rest of the expression. We can do that using the following rules:

  • false && <expression> is short-circuit always evaluated to false.
  • true || <expression> is short-circuit evaluated to true.

This is very handy when you are creating an expression to render something on your screen. I use this all the time in the render() method of my React components. Let's imagine for one moment that you have a variable showErrorMessage that controls whether a message of error should appear on the screen. You can use a short-circuit evaluation to control that.

render(){
  (showErrorMessage) && <h1>Error message</h1>
} 

What this piece of code is doing? If the variable showErrorMessage is true, the Error Message will appear. Otherwise, if the variable is false the rest of the expression is not even evaluated, ergo, the message is not going to appear.

It is important to know that Javascript has six values known as Falsy values, meaning they evaluate to false:

  • false
  • undefined
  • null
  • 0
  • NaN
  • “” (i.e., the empty string)


I hope this can help you as much as It helped me.

Feel free to comment and give feedback


References:

This article is also available at: Medium


To view or add a comment, sign in

More articles by Gustavo Alves

  • Javascript Tips: slice, substr, substring

    When I started studying Javascript, I saw a lot of string manipulation functions that seems to be doing the exact same…

    4 Comments

Explore content categories