0
0
JavascriptComparisonBeginner · 3 min read

== vs === in JavaScript: Key Differences and When to Use Each

In JavaScript, == 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 ConversionPerforms type coercion before comparisonNo type coercion; compares type and value
StrictnessLoose equalityStrict equality
Use CaseWhen type conversion is acceptableWhen exact type and value match is required
Example: '5' == 5truefalse
PerformanceSlightly slower due to type conversionFaster as no conversion happens
Common PitfallCan cause unexpected true resultsSafer 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:

javascript
console.log('5' == 5); // true
console.log(0 == false); // true
console.log(null == undefined); // true
console.log('' == 0); // true
console.log('' == false); // true
Output
true true true true true
↔️

=== Equivalent

Here is how === compares values strictly without type coercion:

javascript
console.log('5' === 5); // false
console.log(0 === false); // false
console.log(null === undefined); // false
console.log('' === 0); // false
console.log('' === false); // false
Output
false false false 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.
Prefer === for safer and clearer equality checks in JavaScript.
Use == only when you explicitly want type conversion in comparison.
Understanding these helps prevent common bugs in JavaScript code.