Javascript logical operators: && ? ||

Today we are going to understand the usage of javascript logical operators &&? and ||.

In order to understand the correct usage of those operators we need to understand what Truthy and Falsy values are. As very well defined by MDN, a Falsy value is a value that translates to false when evaluated in a Boolean context. A Truthy value is translated into true.

Lets see two simple examples

an empty array when evaluated in a boolean context becomes true (Truthy)
an undefined variable when evaluated in a boolean context becomes false (Truthy)

You can find more Truthy and Falsy examples in MDN documentation.

Conditional Operator

Ok now its time to learn about javascript logical operators, lets start with the conditional operator also known as “?”. This operator its often used as a shortcut for a simple if/else statement. Lets how this works and then an example.

condition ? pick_If_True : pick_If_False

In this example we are trying to check if the array parameter was passed. If not, we will initialize it as an empty array (if no parameter is passed it will be undefined). I implemented this using the classic If/Else and the conditional operator. Lets compare it.

As we can see in the example, by using the conditional operator we are only using one line of code and the results are the same.

Logical “OR” operator (||)

Now lets look at the “OR” operator. This selects the first truthy value that it finds. So in this case we can make even shorter our previous example:

Logical “AND” operator (&&)

Finally, the “AND” operator takes the right most truthy value or the first falsy value. That means, the compiler seeks to verify that only truthy values exists, but if it ever arrives at a falsy value, that value gets selected.

When all the elements are truthy it returns the last truthy value found.

Thats it, I hope this was helpful to you. If it was please share.