6

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

return "" && false

returns "".

Why it behaves so ?

3
  • 2
    falsy1 && falsy2 returns falsy1 - lazy evaluation. Commented Aug 13, 2015 at 9:18
  • because Boolean("") === false Commented Aug 13, 2015 at 9:19
  • I already knew this concept of lazy evaluation, but I thought all comparison expression will return boolean value only. Thanks for correcting me. Commented Aug 13, 2015 at 10:56

2 Answers 2

2

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"

Sign up to request clarification or add additional context in comments.

2 Comments

just want to add that because of such behavior it's possible to easily assign default value to function parameter in case it was not passed, like this: function setName(name) { name = name || "default name"; }
@tytyryty While this is naturally possible, ES6 provides us a much cleaner way to do this: function setName(name = "default name") { .... But for non-ES6 you’re right, of course.
0

The LHS is run first and the return exits you from the function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.