Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between == and === in JavaScript?
In JavaScript, == (double equals) performs loose equality comparison with type coercion, while === (triple equals) performs strict equality comparison without type conversion.
Double Equals (==) - Loose Equality
The == operator converts operands to the same type before comparing them. This can lead to unexpected results:
console.log(4 == 4); // true
console.log('4' == 4); // true - string converted to number
console.log(4 == '4'); // true - number converted to string
console.log(0 == false); // true - false converted to 0
console.log('' == false); // true - empty string converted to false
console.log(null == undefined); // true - special case
true true true true true true
Triple Equals (===) - Strict Equality
The === operator compares both value and type without any conversion. It returns false if types differ:
console.log(4 === 4); // true - same type and value
console.log(4 === '4'); // false - different types
console.log(0 === false); // false - different types
console.log('' === false); // false - different types
console.log(null === undefined); // false - different types
let v1 = {'value': 'key'};
let v2 = {'value': 'key'};
console.log(v1 === v2); // false - different object references
true false false false false false
Comparison Table
| Operator | Type Coercion | Performance | Recommended |
|---|---|---|---|
== |
Yes | Slower | Avoid |
=== |
No | Faster | Use always |
Best Practice Example
// Problematic with ==
function checkValue(input) {
if (input == 0) {
return "Zero or falsy value";
}
return "Non-zero value";
}
console.log(checkValue(0)); // "Zero or falsy value"
console.log(checkValue('')); // "Zero or falsy value" - unexpected!
console.log(checkValue(false)); // "Zero or falsy value" - unexpected!
// Better with ===
function checkValueStrict(input) {
if (input === 0) {
return "Exactly zero";
}
return "Not zero";
}
console.log(checkValueStrict(0)); // "Exactly zero"
console.log(checkValueStrict('')); // "Not zero"
console.log(checkValueStrict(false)); // "Not zero"
Zero or falsy value Zero or falsy value Zero or falsy value Exactly zero Not zero Not zero
Conclusion
Always use === for equality comparisons to avoid unexpected type coercion bugs. Use == only when you specifically need type conversion, which is rare in modern JavaScript.
Advertisements
