Skip to content Skip to sidebar Skip to footer

Logical Operators (and Operators)

I came across the following logical operators workaround but could not comprehend the logic behind: console.log(1 && 2) will get you 2 console.log(false && X) will

Solution 1:

Look at the documentation for the && operator:

&&; Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

In the first example, you provide the numbers 1 and 2 as the operands. 1 cannot be converted to false, therefore the second operand, which happens to be 2, is returned.

The two last examples are fairly straightforward, as booleans are involved. If either operand is false, you get back false. The reason only the third one gives you an error is because in the second, the second operand (X) is never checked due to short-circuiting. Short-circuiting means that once JS sees that the first value is false, it does not even bother to check the other value. JS sees false as the first operand and immediately returns.

Solution 2:

So consider the following statement: A && B. What the && operator does here is return Aonly if its value is false otherwise it returns B. That’s how the AND operator works in JavaScript and most other languages for that matter.

So this explains the first 2 lines of code. In the third line, the statement should return the B variable which is X in here. However X seems to be an undeclared variable so the console raises an error.

Solution 3:

In JavaScript, there are truthy and falsy values. The falsy values are

  • false
  • 0 (the number zero),
  • "" or '' (the empty string),
  • undefined and null.

All other values are truthy.

This is how the && operator works in JavaScript:

  1. Evaluate the first operand. If the result is a falsy value, return that value.
  2. Otherwise, evaluate the second operand and return its value.

Let's take a look at your examples:

  • The 1 in 1 && 2 is truthy, so 2 is evaluated and returned as the value of the expression.

  • The false in false && X is falsy, so it is returned as the value of the expression. The second operand (X) will not be evaluated.

  • The true in true && X is truthy, so the second operand is evaluated, which throws an error, because there is no X.

This behavior is very useful if you want to have a fallback value:

functionlogName (options) {
  const name = options.name || 'Default name';
  console.log(name);
}

logName({ name: 'foo' }); // logs 'foo'logName({ name: '' });    // logs 'Default name'logName({});              // logs 'Default name'

Post a Comment for "Logical Operators (and Operators)"