DEV Community

Cover image for Difference between == and === in JavaScript
Ayush Sondhiya
Ayush Sondhiya

Posted on

Difference between == and === in JavaScript

Hello, Dev.to community! As we traverse the realm of JavaScript, we often come across two seemingly similar comparison operators: == (loose equality) and === (strict equality). While they appear to be twins, they differ in some fundamental ways. Let's dive in to uncover the differences.

Loose Equality (==)

The == operator checks for equality after performing any necessary type conversions. This means it will try to convert the values being compared to a common type before making the comparison.

Examples:

"5" == 5  // true, because the string "5" is being type-coerced to the number 5
null == undefined  // true, because null and undefined are considered equivalent
false == 0  // true, because false is type-coerced to 0
Enter fullscreen mode Exit fullscreen mode

Pitfalls:

Due to type coercion, unexpected results can arise:

"" == 0  // true
" \t\r\n" == 0  // true
Enter fullscreen mode Exit fullscreen mode

Strict Equality (===)

The === operator, also known as the identity or strict equality operator, checks for equality without performing type conversion. If the values being compared have different types, the comparison will always return false.

Examples:

"5" === 5  // false, no type coercion is performed
null === undefined  // false, they are of different types
false === 0  // false, different types
Enter fullscreen mode Exit fullscreen mode

Sorry for interruption :-

follow US on WhatsApp For regular updates - WhatsApp ScriptSquad
YouTube Channel - ScriptSquad 01

Advantages:

Using === can prevent unexpected results due to type coercion, making it a safer choice for most comparisons in JavaScript.

Which One to Use?

If you're certain about the types of variables you're comparing and want to allow type coercion, == might be acceptable.

However, in most scenarios, it's recommended to use === to avoid unforeseen results caused by type coercion.

Conclusion

Understanding the difference between == and === in JavaScript is vital for writing predictable and bug-free code. As a best practice, lean towards using === for your comparisons unless there's a specific reason to allow type coercion.

Happy coding!

Top comments (0)