sidanmor sidanmor - 7 days ago 3x
Javascript Question

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

I don't know what is better to use:

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

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

Thanks for the help


You are actually comparing two separate things, in first, you are casting both the variable values to a string and comparing, and the other comparison is lose one 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 a same value.

According to me, what you should be using is === which will not only compare the values but their data types as well because the ones you are using are both considered lose.

If you do not consider at all about data type then using == will suffice. You don't have to cast the values to a string.