I'm fairly new to Javascript and I would like to know why '1' == true returns true but '2' == true returns false. Coming from Java background, type coercion in Javascript has been quite difficult to grasp
Asked
Active
Viewed 1,025 times
2
-
this may help: https://stackoverflow.com/questions/12236271/is-true-1-and-false-0-in-javascript – Calvin Nunes Jul 29 '19 at 16:44
-
1Get used to always using `===` for strict equality – charlietfl Jul 29 '19 at 16:47
2 Answers
3
My answer is based off this table.
In your example, operand A is a String, and operand B is boolean. So then it calls ToNumber
on both of them and compares them for strict (===
) equality.
ToNumber('2') === 2
, but ToNumber(true) === 1
, so the two are not equal.
A more in-depth explanation of the implementation is here.

Calvin Godfrey
- 2,171
- 1
- 11
- 27
-
Why, when A is a string and B is a boolean, does it decide to call 'ToNumber' to decide equality, rather than, say, 'toString'? – TKoL Jul 29 '19 at 16:49
-
1Because that's what they decided when they wrote the standard, that's really all there is to it. You can read the technical standard's section on [equality](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9), though it's not much more illuminating. – Calvin Godfrey Jul 29 '19 at 16:51
-
0
basically it comes down to truthy and falsy values in Javascript.
since your comparison is done with == this basically means just value comparison.
among other things in Javascript, true is equal to 1 in value, just like false is equal to 0 in value. also, given the fact that u used == instead of ===, it's the same as 1 == '1' but 1 !== '1'.

Ionut Ardelean
- 478
- 4
- 9