2

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

Aboagye
  • 53
  • 1
  • 5

2 Answers2

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
  • 1
    Because 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
  • I get it now. thanks @CalvinGodfrey for the enlightenment – Aboagye Jul 29 '19 at 17:05
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