Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Strange behaviour `empty string` AND `false` returns empty string

Tags:

javascript

Today I came across the strange behaviour in Javascript. Below is the code

return "" && false

returns "".

Why it behaves so ?

like image 461
Kamalakannan J Avatar asked Aug 13 '15 09:08

Kamalakannan J


1 Answers

Because

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).

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"

like image 173
idmean Avatar answered Oct 04 '22 03:10

idmean