Today I came across the strange behaviour in Javascript. Below is the code
return "" && false
returns "".
Why it behaves so ?
Because
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
ECMAScript 5.1
This means:
Return the first value if it is falsy, return the second value if the first is truthy.
This is also the behavior seen if you do:
return false && true
You get false
.
This means also that this
return 23 && "Hello"
would give you "Hello"
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