JavaScriptEasy
What is the difference between == and ===?
=== (strict equality) compares value and type with no conversion; == (loose equality) converts the operands to a common type first, which leads to surprising results.
How == converts
The rules are long, but the common cases are:
null == undefinedistrue, and neither equals anything else.- If one side is a number and the other a string, the string is converted to a number.
- Booleans are converted to numbers first (
true→ 1,false→ 0). - Objects are converted to primitives (via
valueOf/toString) before comparing.
That is why "" == 0, "0" == false and [] == false are all true, yet "" == "0" is false. Loose equality is not even transitive.
What === still does not handle
NaN === NaNisfalse. UseNumber.isNaN(x).+0 === -0istrue. UseObject.is(a, b)if the difference matters.- Objects are compared by reference, so two equal-looking objects are not
===.
Object.is is "same value" equality: like === but Object.is(NaN, NaN) is true and Object.is(0, -0) is false.
Best practice
Always use ===. The one widely accepted exception is value == null, which checks for both null and undefined in one go.
Code example
js
1console.log(5 == "5"); // true (string converted to number)2console.log(5 === "5"); // false (different types)34console.log("" == 0); // true5console.log("0" == false); // true6console.log("" == "0"); // false <- loose equality is not transitive7console.log([] == false); // true89console.log(null == undefined); // true10console.log(null === undefined); // false11console.log(null == 0); // false1213console.log(NaN === NaN); // false14console.log(Number.isNaN(NaN)); // true15console.log(Object.is(NaN, NaN)); // true16console.log(Object.is(0, -0)); // false1718// The accepted shortcut: check for null OR undefined19function hasValue(x) {20 return x != null;21}22console.log(hasValue(0), hasValue(""), hasValue(null), hasValue(undefined)); // true true false false
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.