What is the difference between == and === in JavaScript?
Quick answer
== compares values after type coercion, while === compares both value and type with no conversion, so it is the safer default.
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.
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)Key points
- === checks type and value, == coerces first
- Prefer === everywhere except deliberate null checks
- Objects are compared by reference, not by content
Questions interviewers ask next
- How do you compare two objects for equality?
- What does Object.is do differently?