0

I know the meaning of ===: it will check whether the operands are identical or not,so

  • 1 === '1' will give false and
  • 1 == '1' will give true,

But typeof 1 is number and typeof '1' is string, so how is JavaScript comparing 1 == '1'? Are there any conversions happening? If so, which ones?

Mathieu K.
  • 283
  • 3
  • 14
user2131316
  • 3,111
  • 12
  • 39
  • 53

3 Answers3

4

If types are number and string,

JavaScript will convert the string to a number.

Out of Annotated ECMAScript 5.1:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

...

5. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y). 6. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

idmean
  • 14,540
  • 9
  • 54
  • 83
0

You can do 1 == parseInt("1") to parse the string into an integer.

Andrew
  • 2,013
  • 1
  • 23
  • 38
0

Use String()

It converts the input to a string before doing a comparison.

Example:

var test1= 1;
var test2= "1";

var answer = String(test1) === String(test2);

Answer will equal true in this case.

Adam Botley
  • 672
  • 7
  • 14
  • yes, but if you only type 1 == '1', it will be true, so how javascript compare it? does javascript will convert the test1 to string automatically? – user2131316 Sep 27 '13 at 14:01
  • This answers your question a bit better then, I thought you were wanting to know how to convert the values before comparing! http://stackoverflow.com/a/7625195/2509123 – Adam Botley Sep 27 '13 at 14:06