Understanding the && and || Operators in JavaScript
JavaScript defines the two operators && and || which represent the logical AND and OR operations, respectively. Using only the two boolean values true and false.
If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).
However, can you use && and || with operands other than booleans? Turns out, you can!
This post explains in detail how && and || operators work in JavaScript.
Before jumping into how the operators work, let’s start with the basic concepts of truthy and falsy.
1. Falsy Value
Because JavaScript is a loosely typed language, logical operations can be performed on any type. The expressions like 1 && 2, null || undefined, 'hello' && true are weird, but still valid in JavaScript.
To perform logical operations on any type, JavaScript decides whether a particular value can be considered falsy (an equivalent of false) or truthy (an equivalent of true).
Falsy is a value for which Boolean(value) returns false. Falsy values in JavaScript are only false, 0, '', null, undefined and NaN.
2. Truthy Value
Truthy is a value for which Boolean(value) returns true. Saying it differently, truthy are the non-falsy values.
Examples of truthy values are true, 4, 'Hello', { name: 'John' } and everything else that’s not falsy.
Now lets jump in to how the operators work:
How && operator works.
Now let’s continue with proper learning of how && operator works. Note that the operator works in terms of truthy and fasly, rather than true and false.
Syntax:
expr1 && expr2
Description:
If expr1 can be converted to true, returns expr2; else, returns expr1.
If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.
Example 1:
The evaluation is performed from left to right. 3 and 1 are passed because they are truthy. But the evaluation stops at the third operand 0 since it’s falsy. 0 becomes the result of the entire expression. The fourth operand 10 is not evaluated.
Example 2:
How || operator works.
|| works the same way as &&, with the only difference that || stops evaluation when encounters a truthy operand.
Syntax:
expr1 || expr2
Description:
If expr1 can be converted to true, returns expr1; else, returns expr2.
If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.
Example 1:
The first operand 0 is falsy, so the evaluation continues. The second argument -1 is already truthy, so the evaluation stops, and the result is -1.
Example 2:
Thanks for reading this post, I hope you enjoyed and learned something.👍