Which is better to use: "2" .toString () === 2.toString () OR "2" == 2?

I don't know which is better to use:

var s = "2";
var i = 2;
if(s.toString() === i.toString()){
    //do something
}
//OR

if(s == i){
    //do something
}

      

thanks for the help

+3


source to share


2 answers


You are actually comparing two separate things: first, you are casting the values โ€‹โ€‹of the variables into a string and comparing, and the other comparison is lost, i.e. you are not actually checking the data types of those variables. so it will return true if you compare string

with int

with the same value.

In my opinion, you should use ===

which will not only compare values, but their data types as well, because the ones you use are considered lost.



If you are not considering data type at all, then using ==

. You don't need to supply values โ€‹โ€‹in string

.

+4


source


In the first example, if for any reason you get 2 with a space, it will evaluate to false (even with ==):

var s = " 2"; // 2 with a sneaky space
var i = 2;
if(s.toString() === i.toString()){ // will be false
    //do something
}

      

Personally, I prefer to use ===, but I would change the values โ€‹โ€‹to integers rather than strings.



var s = " 2"; // 2 with a sneaky space again
var i = 2;
if(Number(s) === Number(i)){ // will be true
    //do something
}

      

You don't need the second Number (), but I don't know, you can get data that is also a string.

+1


source







All Articles