|| Converting Empty String To Bool, && Not
Solution 1:
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"
Solution 2:
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 && BitwiseORExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingLogicalANDExpression
.- Let
lval
beGetValue(lref)
.- If
ToBoolean(lval)
isfalse
, returnlval
.- Let
rref
be the result of evaluatingBitwiseORExpression
.- Return
GetValue(rref)
.The production
LogicalORExpression : LogicalORExpression || LogicalANDExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingLogicalORExpression
.- Let
lval
beGetValue(lref)
.- If
ToBoolean(lval)
istrue
, returnlval
.- Let
rref
be the result of evaluatingLogicalANDExpression
.- Return
GetValue(rref)
.The
LogicalANDExpressionNoIn
andLogicalORExpressionNoIn
productions are evaluated in the same manner as theLogicalANDExpression
andLogicalORExpression
productions except that the containedLogicalANDExpressionNoIn
,BitwiseORExpressionNoIn
andLogicalORExpressionNoIn
are evaluated instead of the containedLogicalANDExpression
,BitwiseORExpression
andLogicalORExpression
, 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.
Solution 3:
The ||
operator will return the first value which is truthy.
The &&
operator will return the second value if the first is truthy, otherwise it returns the first.
For more info, you can see the Logical Operators page on the MDC site.
In your case,
'' || true
;''
is false, so the||
operator moves onto the second value, which is true, and so returns it.'' || false
;''
is false, so the||
operator moves onto the second value, which is false, and has no more values to compare, so returns it.'' && false
; the first value (''
) is falsy, so it returns it.'' && true
; the first value (''
) is falsy, so it returns it.
Post a Comment for "|| Converting Empty String To Bool, && Not"