0
var number = 2;
var string = '2';
if (number == string){
    return true;
}

The code above will return true. I was wondering how the == operator works. Will it convert the integer to string and then do the comparsion or the oposite?

seaotternerd
  • 6,298
  • 2
  • 47
  • 58
Rados
  • 481
  • 4
  • 17
  • http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Johnathan Ralls Apr 18 '15 at 13:15
  • This has been asked before, [checkout post about type coercion in JS.][1] [1]: http://stackoverflow.com/a/359509/554389 – Ivo Apr 18 '15 at 13:38

3 Answers3

0

== operator does change the data type. we can use parseInt in JavaScript for number and toString for string

If we compare like that it always return false :-

var number = parseInt("2");
var string = '2';
var str=string.toString;
if (number == str){
   return TRUE;
}else{
   return FALSE;
}
Saty
  • 22,443
  • 7
  • 33
  • 51
  • Of course that does return `FALSE` (which throws an `undefined variable error`), because you are comparing a function to a number. – Bergi Apr 18 '15 at 14:13
0

you must define the base when you use the parseInt function and use the === to compare the strict equality :

var number = parseInt('2', 10);
var string = '2';
return (number === string);
Nicolas Pennec
  • 7,533
  • 29
  • 43
0

I was wondering how the == operator works. Will it convert the integer to string and then do the comparison or the opposite?

No, it will convert the string to a number and then do the comparison.

You can read the exact Abstract Equality Algorithm in the spec if you want.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375