== vs === in JavaScript: Key Differences and When to Use Each
== compares two values for equality after converting their types if needed, while === compares both value and type strictly without conversion. Use === to avoid unexpected results caused by type coercion.Quick Comparison
This table summarizes the main differences between == and === in JavaScript.
| Feature | == (Double Equals) | === (Triple Equals) |
|---|---|---|
| Type Conversion | Performs type coercion before comparison | No type coercion; compares type and value |
| Strictness | Loose equality | Strict equality |
| Use Case | When type conversion is acceptable | When exact type and value match is required |
| Example: '5' == 5 | true | false |
| Performance | Slightly slower due to type conversion | Faster as no conversion happens |
| Common Pitfall | Can cause unexpected true results | Safer and more predictable |
Key Differences
The main difference between == and === lies in how they compare values. The == operator performs type coercion, meaning it converts the values to a common type before comparing. For example, the string '5' and the number 5 are considered equal with == because the string is converted to a number first.
On the other hand, === checks both the value and the type without any conversion. So, '5' === 5 is false because one is a string and the other is a number. This strict comparison helps avoid bugs caused by unexpected type conversions.
Because == can lead to confusing results, many developers prefer using === to ensure their comparisons are clear and predictable.
Code Comparison
Here is how == compares values with type coercion:
console.log('5' == 5); // true console.log(0 == false); // true console.log(null == undefined); // true console.log('' == 0); // true console.log('' == false); // true
=== Equivalent
Here is how === compares values strictly without type coercion:
console.log('5' === 5); // false console.log(0 === false); // false console.log(null === undefined); // false console.log('' === 0); // false console.log('' === false); // false
When to Use Which
Choose === when you want to be sure both the value and type match exactly, which helps prevent bugs and makes your code easier to understand. Use == only if you intentionally want to allow type conversion and are confident about the types involved. In most cases, === is the safer and recommended choice.
Key Takeaways
=== checks both value and type strictly, avoiding unexpected results.== allows type coercion, which can cause confusing true comparisons.=== for safer and clearer equality checks in JavaScript.== only when you explicitly want type conversion in comparison.