Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

|| converting empty string to bool, && not

Is this normal? Is it a feature or a bug? (I'm using firebug):

>>> '' || true
true
>>> '' || false
false
>>> '' && false
""
>>> '' && true
""
like image 647
Paolo Avatar asked Nov 25 '25 12:11

Paolo


2 Answers

It is not converting the empty string to Boolean.

With ||

It is evaluating the left hand side, of which an empty string is falsy. It then checks the right hand side (because it's an or, and that side may be true), and returns that value.

With &&

Because && needs both sides to be true and the left hand side is falsy, it doesn't bother checking the right hand side (short circuit evaluation). Therefore, it just returns the left hand side, which is the empty string.

JavaScript always returns the last value it evaluated.

>>> '' || 0 || undefined || null || false || NaN || 'hello'
"hello"
like image 55
alex Avatar answered Nov 28 '25 01:11

alex


It's not that one is converting and the other isn't; the lines with || are returning their second operand and the lines with && are returning their first, due to short-circuiting.

[ECMA-262 11.11]: Semantics

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalANDExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is false, return lval.
  4. Let rref be the result of evaluating BitwiseORExpression.
  5. Return GetValue(rref).

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalORExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is true, return lval.
  4. Let rref be the result of evaluating LogicalANDExpression.
  5. Return GetValue(rref).

The LogicalANDExpressionNoIn and LogicalORExpressionNoIn productions are evaluated in the same manner as the LogicalANDExpression and LogicalORExpression productions except that the contained LogicalANDExpressionNoIn, BitwiseORExpressionNoIn and LogicalORExpressionNoIn are evaluated instead of the contained LogicalANDExpression, BitwiseORExpression and LogicalORExpression, respectively.

NOTE The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.

like image 37
Lightness Races in Orbit Avatar answered Nov 28 '25 01:11

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!