0

I was reading some tricky javascript output question and found that

console.log(2 && 3) is 3

There is no explanation for the same. Shouldn't it be true?, as value of both the numbers being non zero should be type casted as true

Rhythm Walia
  • 161
  • 2
  • 9
  • 2
    `(a && b) == (a ? b : a)` and `(a || b) == (a ? a : b)`. –  Sep 18 '16 at 13:08
  • 3
    `&&` gives the first `false` starting from the very left. If none, it'll return the last one – choz Sep 18 '16 at 13:08
  • 1
    In javascript only flow control statements like `if`,`while` do implicit typecasting to boolean – Anirudha Sep 18 '16 at 13:13
  • @Anirudha Nope. `&&` and `||` also do implicit typecasting *for flow control*, [at least since ES5](https://es5.github.io/#x11.11). –  Sep 18 '16 at 21:16
  • @Rhymoid no they dont.. am qouting this in the doc you shared here..its mentioned that " The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand".. later if this expression is inside a flow control statement, it will be type casted via `toBookean` ..this behaviour is also mentioned in the doc you shared under if condition section – Anirudha Sep 19 '16 at 05:05

1 Answers1

2

It's just the way the language works. It is well documented.

Per MDN:

Logical AND (expr1 && expr2) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.

Luke
  • 5,567
  • 4
  • 37
  • 66