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?
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?
== 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;
}
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);
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.