DEV Community

Discussion on: == (or) ===? What do you prefer and why?

Collapse
 
talk2megooseman profile image
Erik Guzman • Edited

== and === are different operators. It's not about preferences but how you want to enforce equality.

When using ==, JavaScript will do type coercion to see if both values are equal to each other. This will have unfortunate side effects, depending on how you use it.

For example, take the value 1 and the string "1". Are these to values equal? No, not really. One is a string, and one is a number.

Let's see what using == has to say. If you go into your console or launch node and type in 1 == "1" you should see the following.

> 1 == "1"
true

Dang, that isn't right!

Now, let's take a look at ===. The === operator does exact equality checking, no type coercion. If you go back to run the code 1 === "1" well see the following

> 1 === "1"
false

That more like it! You should always default to using === to ensure equality checks are making exact comparisons. Sometimes you might need to use == but those situations are going to be pretty limited.

An example of a special case like that is a comparison of a string literal and a String object.

> "abc" == new String("abc")  
true

> "abc" === new String("abc")  
false
Collapse
 
hycarldev_ profile image
Haikal Azmi

Thanks!