What is the difference between `==` and `===`?
Show answer — try answering out loud first
=== compares value and type without converting anything (strict equality). == converts the types before comparing (loose equality with coercion). The recommendation is to always use ===.
===(strict equality): it only returnstrueif both values are of the same type and have the same value. It does no conversion.==(loose equality): if the types differ, JavaScript tries to convert them to a common type before comparing. This produces surprising results.
That's why the general recommendation is to use ===: it's predictable and avoids errors.
// === compares value and type
console.log(5 === 5); // true
console.log(5 === "5"); // false (number vs string)
// == converts the types before comparing
console.log(5 == "5"); // true ("5" is converted to 5)
console.log(0 == false); // true (false is converted to 0)
console.log("" == false); // true (both are converted to 0)
console.log(null == undefined); // true (special case)
// Cases that are confusing with ==
console.log([] == false); // true
console.log(" " == 0); // true (the space is converted to 0)
// With === everything is more predictable
console.log(0 === false); // false
console.log(null === undefined); // false
Using == "because it works" in simple cases and then running into weird bugs like [] == false being true. The coercion rules of == are hard to remember and lead to subtle errors.
"
===is strict equality: it compares value and type without converting.==is loose equality: if the types don't match, JavaScript converts one of them before comparing, which produces unexpected results like0 == falsebeing true. I always use===because it's predictable; I would only use==on purpose for a specific case, likevalor == nullto check for null and undefined at the same time."
Predict each result:
console.log(1 == true);
console.log(1 === true);
console.log("0" == 0);
console.log("0" === 0);
See answer
true, false, true, false. With == there is coercion (true is converted to 1, "0" to 0); with === the types differ, so it's false.