Short circuiting in Javascript

ยท

3 min read

Short circuiting in Javascript

Photo by Vlad Panov on Unsplash

Short circuiting is a very important topic for beginners. It is very useful and you will also use it in React, or other JS frameworks too.

Truthy and falsy values

james-harrison-vpOeXr5wmR4-unsplash.jpgPhoto by James Harrison on Unsplash

First, we need to understand what True and False values are. Values that return true are truth values and those which return false are falsy values.

Let's take an example:

console.log(!!'hello')

It returns true, so it is a truth value. In fact, there are only 6 important falsy values, which are:-

  1. Null
  2. Undefined
  3. 0
  4. "", '', ``
  5. NaN
  6. false, of course

The other falsy values are -0, 0n, and document.all(it depends)

The && operator

Let's talk about what the && operator is. So the and operator gives true if all the values are true, else it gives false.

So, according to that, it just returns the first false value it finds and stops there. If the other values are true, it takes the last one. Let's take some examples:

console.log(false && true) // false
console.log("" && "Hello") // ""
console.log("" && 0) // ""
console.log("Hi" && "Hello") // "Hello"
console.log("Hello" && 0) // 0

Use of it?

What's the use of it? Well, we use it a lot, especially in React.js. In React, we use it to render a component or any JSX code if a variable is true or false. This way, we can decrease the lines of code we have and work more efficiently. I will not go into the code here as it is not the topic of this blog.

The || operator

Let's talk about what the || operator is. So the and operator gives true if any of the values are true, else it gives false.

So, according to that, it just returns the first true value it finds and stops there. If the other values are false, it takes the last one. Let's take some examples:

console.log(false || true) // true
console.log("" || "Hello") // "Hello"
console.log("" || 0) // 0
console.log("Hi" || "Hello") // "Hi"
console.log("Hello" || 0) // "Hello"

Use of it?

What's the use of it? Well, you can use it to make default values. For example, you want to give a variable a default value if the value you want to give it is falsy. Let's see another example:

const zebra = 0 || 'cool ๐Ÿฆ“' // cool ๐Ÿฆ“

So now we know about short circuiting in JS. See you later.

A HUGE thank you ๐ŸŽŠ๐ŸŽŠ๐ŸŽ‰๐ŸŽ‰๐Ÿฅณ๐Ÿฅณ

I want to thank all my followers, commenters, reactors, and viewers a huge thanks. It's just 'cause of you I am able to make this stuff.๐Ÿ’ช๐Ÿ’ช๐Ÿ’ช๐Ÿ’ช

Did you find this article valuable?

Support Raghav Singh Gulia's Blog by becoming a sponsor. Any amount is appreciated!

ย