0

Why is 1=='true' false?

If 1=='1' is true and 1==true is true.

If JavaScript compares only values not the types in the == scenario.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    @user1805928 Because `true != 'true'`...? – Biffen Dec 08 '15 at 13:16
  • 3
    I honestly don't understand why this question is down voted. The poster asked a valid - and very educative - question that would help a lot while bug fixing. If you think this question is silly - or obvious, I encourage them to give an answer and explain instead. – AVAVT Dec 08 '15 at 13:17
  • Please look at the following... http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Mike Sav Dec 08 '15 at 13:18
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators – deceze Dec 08 '15 at 13:19
  • 1
    http://stackoverflow.com/questions/28571451/equality-of-truthy-and-falsy-values-javascript – epascarello Dec 08 '15 at 13:20

1 Answers1

11

It's because of type coercion.

In effect, this is what JavaScript is trying to do on your behalf when using the == operator.

1 == Number('true'); // 1 == NaN

1 == Number('1'); // 1 == 1

1 == Number(true); // 1 == 1

When two different types are compared using ==, JavaScript attempts to coerce them to the same type for comparission.

You can read more about the algorithm here: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html

Josh
  • 44,706
  • 7
  • 102
  • 124