Is this normal? Is it a feature or a bug? (I'm using firebug):
>>> '' || true
true
>>> '' || false
false
>>> '' && false
""
>>> '' && true
""
It is not converting the empty string to Boolean.
||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.
&&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"
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]:SemanticsThe production
LogicalANDExpression : LogicalANDExpression && BitwiseORExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingLogicalANDExpression.- Let
lvalbeGetValue(lref).- If
ToBoolean(lval)isfalse, returnlval.- Let
rrefbe the result of evaluatingBitwiseORExpression.- Return
GetValue(rref).The production
LogicalORExpression : LogicalORExpression || LogicalANDExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingLogicalORExpression.- Let
lvalbeGetValue(lref).- If
ToBoolean(lval)istrue, returnlval.- Let
rrefbe the result of evaluatingLogicalANDExpression.- Return
GetValue(rref).The
LogicalANDExpressionNoInandLogicalORExpressionNoInproductions are evaluated in the same manner as theLogicalANDExpressionandLogicalORExpressionproductions except that the containedLogicalANDExpressionNoIn,BitwiseORExpressionNoInandLogicalORExpressionNoInare evaluated instead of the containedLogicalANDExpression,BitwiseORExpressionandLogicalORExpression, respectively.NOTE The value produced by a
&&or||operator is not necessarily of typeBoolean. The value produced will always be the value of one of the two operand expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With