< BACK TO QUESTIONS

What is the difference between == and === in JavaScript?

Faraz

By Faraz - June 06, 2023

Discover the dissimilarity between the == and === operators in JavaScript.


In JavaScript, the "==" and "===" operators are used for comparison, but they have different behaviors.


The "==" (double equals) operator is called the "loose equality" or "abstract equality" operator. It compares the values on both sides after performing type conversion if necessary. This means that if the compared values are of different types, JavaScript will try to convert them to a common type before making the comparison. For example, the string "2" and the number 2 would be considered equal when using the "==" operator because JavaScript would convert the string to a number before comparing them.


On the other hand, the "===" (triple equals) operator is called the "strict equality" or "strict comparison" operator. It compares the values on both sides without performing type conversion. It checks both the values and the types of the compared expressions. For the comparison to return true, both the values and types must be identical. For example, the string "2" and the number 2 would be considered not equal when using the "===" operator because they have different types.


Here are a few examples to illustrate the difference:


console.log(2 == "2");   // true (type conversion is performed)
console.log(2 === "2");  // false (different types)

console.log(true == 1);  // true (type conversion is performed)
console.log(true === 1); // false (different types)

In general, it is recommended to use the "===" operator for equality comparisons in JavaScript because it avoids unexpected behavior due to type coercion. It provides a stricter and more predictable comparison.


Here's a table summarizing the differences between the two operators:


Operator Description Example
== Equality operator with type coercion 5 == "5" returns true
=== Strict equality operator without type coercion 5 === "5" returns false

I hope you found the above information helpful. Please let me know in the comment box if you have an alternate answer πŸ”₯ and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post