Sunday, March 13, 2022

Logical Operators in Javascript (Part-I)

 

In this blog, we will learn about logical operators in JavaScript.

Trust me, it's going to be an amazing journey as logical operators in JavaScript are a little different 👿


We have 4 logical operators as below : 

  • OR ( || ) 
  • Null Coalescing ( ?? ) 
  • AND ( && ) 
  • NOT ( ! ) 

We will learn about the OR operator first.

  1. OR ( || )

In most languages OR is supposed to be used with Boolean values and give out only Boolean values ie return TRUE if any of the operands are TRUE else return FALSE ie 

    • TRUE || TRUE  -- > TRUE 
    • FALSE || TRUE --> TRUE 
    • TRUE || FALSE -- > TRUE 
    • FALSE || FALSE --> FALSE

But in JavaScript this operator works a little differently, we can not only use it Boolean operands but also with everything else as well ( any data type).

And No output will also not be necessarily Boolean rather can be any data type 🤯

OR operator works on the basis of truthy and falsy values (Refer to MDN docs if you need a refresher on truthy and falsy values)

Now let's look at the OR operator working. It evaluates all operands from left to right. If the left operand is truthy value. It will return it else it will return 2nd operand. 

If I try to put the above statement in other words, we already know that the OR operator returns TRUE unless both operands are FALSE ie 

If the first operand is a truthy value, it doesn't matter what the next operand is as output is going to be a truthy value or say first operand.

Only if the first operand is falsy value, now output will depend on 2nd operand. If it's truthy value it will lead to truthy value else a falsey value.

Let's look at some examples. 


We only discussed and saw examples, when we have only 2 operands but what If we have chain of operands. What happens in that case? 

Well, OR operator still acts the same and traverses from L-R searching for truthy values, and as soon as a truthy value is found it's returned else it keeps on moving towards the end of the chain and if no truthy value is found it returns the last value.

Let's look at an example


 

Note: While processing from L to R as soon as the first truthy value is returned and all the other operands are left untouched, this is called short-circuiting.

Let's take a look at another example to understand short-circuiting better.


If you notice in the above example fun1 and fun2 were never even executed because of short-circuiting.

Note: Remember in the JavaScript output of OR operator is not going to be necessarily Boolean rather will depend on which operand will get returned after evaluation and can lead to any data type


Thanks.

If you liked the post do support me by buying a pizza for me :D.

 

 

No comments:

Post a Comment