JavaScript ==
vs ===
: Key Differences Explained
Understanding the difference between ==
(loose equality) and ===
(strict equality) is crucial for writing bug-free JavaScript code. Let’s break it down with examples.
1. ==
(Loose Equality)
Performs type coercion before comparing values. This means JavaScript converts types to match, which can lead to unexpected results.
Examples:
5 == '5'; // true (string '5' coerced to number)
true == 1; // true (boolean true coerced to 1)
null == undefined; // true (special case)
'0' == false; // true (both coerced to 0)
When to Use: Rarely. It can introduce subtle bugs due to implicit type conversion.
2. ===
(Strict Equality)
Checks both value and type without coercion. Safer and more predictable.
Examples:
5 === '5'; // false (number vs string)
true === 1; // false (boolean vs number)
null === undefined; // false (different types)
'0' === false; // false (string vs boolean)
When to Use: Always prefer ===
unless you explicitly need type coercion.
Key Takeaways
==
checks values after type coercion (risky).===
checks values AND types (recommended).- Avoid bugs by defaulting to
===
.
Interview Question:
Q: Why does [] == ![]
return true
in JavaScript?
A: Due to type coercion! ![]
becomes false
, and []
coerces to ""
then 0
, while false
coerces to 0
. Hence, 0 == 0
is true
.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.