Why does this code produce 3 in JavaScript?

javascript, operators

Solution

This is to be expected.

In JavaScript (and many other languages), not only Booleans themselves are true or false, but other objects can be truthy or falsey as well (See the docs on mdn):

The value […] is converted to a boolean value, if necessary. If value is […] is `0`, `-0`, `null`, `false`, `NaN`, `undefined`, or the empty string (`""`), [it is] false. All other values, including any object or the string `"false"`, create […] true.

The logical operators `||` and `&&` don't return `true` or `false`, rather they return the last argument to influence whether they are truthy or falsey (reference):

- `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 are true; otherwise, returns false.

- `expr1 || expr2` – Returns `expr1` if it can be converted to true; otherwise, returns `expr2`. Thus, when used with Boolean values, `||` returns true if either operand is true; if both are false, returns false.

Problem

Why does the following code produce `a == 3`? ``` var x = "abc"; var y = 3; var z = "xyz"; var a = x && y || z; ``` http://jsfiddle.net/thinkingmedia/qBZAL/ I would have expected this to result in `a == true`. Why is the logical operator evaluating `"abc"` as `true` but doesn't evaluate `3` as `true`. Instead it produces `3` as the result. Furthermore, if you change `y = 0` then `a == "xyz"` which means that `&&` treated `0` as `false`. What happen to treating a number as a number? What's going on here with the logical operators?

Original source