DEV Community

lfriedrichs
lfriedrichs

Posted on

Why you should use === and not == in JS

I'm currently in Flatiron School's Immersive Software Engineering Bootcamp. We began with RUBY where == is totally fine to use in equality statements. We have no switched to JavaScript and with it comes an important difference. In JavaScript the default equality comparison is ===, where as a special equality case (==) can be used where appropriate.

Here is a link to mozilla's explanation on the subject. To highlight their content, here's a summary.

=== is a strict equality comparison while == is an abstract equality comparison. Because == is abstract, you should only use it in special cases WHERE YOU WANT THE DESIRED BEHAVIOR. 3 === '3' will return FALSE as expected but 3 == '3' will return TRUE. For simple comparison this is fine, but as you get deep into your application you may unintentionally create an error when you receive unexpected input, or if you are using a conditional to control your input it might not filter out a case for which you did not account. So in short, it's good practice to stick with the === unless you have a specific reason to use ==.

Top comments (2)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Performance-wise, === might also be faster than ==.

Collapse
 
tremainebuchanan profile image
Tremaine Buchanan

Great post! I think you should also add that === checks both the data types and values of the operands while == only checks the value of the operands.