Which is better to use: "2" .toString () === 2.toString () OR "2" == 2?
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
.
source to share
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.
source to share