What is the difference between == and === in JavaScript?
- Technology:
- JavaScript
- Topics:
- Programming Fundamentals
Quick answer
== compares values after type coercion, while === compares both value and type with no conversion, so it is the safer default.
Detailed explanation
The loose equality operator == converts the operands to a common type before comparing, which leads to surprising results such as 0 == '' and null == undefined both being true. The strict equality operator === returns false immediately if the types differ.
Most teams enforce === with a lint rule. The one commonly accepted use of == is value == null, which checks for both null and undefined in one expression.
Neither operator compares objects by content. Two separate objects or arrays with identical contents are never equal, because both operators compare references.
Example
0 == ""; // true (both coerced to 0)
0 === ""; // false (number vs string)
null == undefined; // true
null === undefined; // false
NaN === NaN; // false (use Number.isNaN)
[1] === [1]; // false (different references)How to explain it in an interview
Triple equals compares type and value with no conversion; double equals coerces both sides to a common type first, which produces surprises like 0 == "" being true. I use === everywhere and only allow == null as a short way to check for null or undefined.
Key points
- === checks type and value, == coerces first
- Prefer === everywhere except deliberate null checks
- Objects are compared by reference, not by content
Common mistakes
- Thinking === compares objects or arrays by content. Both operators compare references.
- Using === to check for NaN. NaN is never equal to itself; use Number.isNaN.
Follow-up questions
- How do you compare two objects for equality?
- What does Object.is do differently?