
== vs === Isn't 'Value vs Type': How JavaScript Equality Really Works
- كاتب موثّق
- ES2025
محتويات المقال
if (limit == 0), and limit comes straight from the input's value. A teammate changes it to === because the linter complains, and now typing 0 doesn't show "Unlimited" either. Neither operator was the bug. The code compared a string with a number and never decided what an empty field means.
The common misconception
=== compares value and type, == compares the value and ignores the type, and that's all there is to equality. Use === everywhere and the problem goes away.
== doesn't ignore types; it converts one operand to match the other in specific steps, and those steps are what make "" == 0 true and "true" == true false. And === doesn't compare "values" the way people picture it: two objects with the same contents are not equal, and NaN isn't even equal to itself.
What actually happens
When the types match, == is ===
== through an abstract operation called IsLooselyEqual. Its very first step says: if both operands have the same type, return IsStrictlyEqual, the operation behind ===. So x == y and x === y can only disagree when x and y have different types. Comparing two strings, two numbers or two objects with == is exactly a === comparison, with no conversion at all.
When they don't, == follows a short list of conversions
nullandundefinedare equal to each other and to nothing else, not even0orfalse.A number against a string: the string becomes a number. An empty or whitespace-only string becomes 0, and something like"12px"becomes .A boolean on either side becomes a number first: trueis1,falseis0.An object against a primitive: the object is converted to a primitive. An array becomes its comma-joined string, so []becomes"".A BigInt is compared with a number by mathematical value, and with a string after parsing the string as a BigInt. Any other mix, such as a symbol against a string, is not equal.
"true" == true doesn't ask whether the string looks truthy: true becomes 1, then "true" becomes NaN, and NaN equals nothing. This automatic conversion is called , and it explains every "weird" == result people love to share.
=== has its own rules for numbers and objects
false for different types. For two numbers it uses numeric equality, where NaN is not equal to any value, itself included, and +0 equals -0. For everything else it checks whether both sides are the same value, and for objects that means the same object in memory, known as . Two { id: 1 } literals are two different objects, with == or ===:
console.log("" == 0); // true: "" converts to the number 0console.log("true" == true); // false: true → 1, "true" → NaNconsole.log([] == false); // true: [] → "" → 0, false → 0console.log(null == 0); // false: null only equals undefinedconsole.log(NaN === NaN); // false: NaN equals nothingconsole.log({ id: 1 } === { id: 1 }); // false: two different objectsconsole.log([NaN].indexOf(NaN)); // -1: indexOf uses ===console.log([NaN].includes(NaN)); // true: includes uses SameValueZeroFour comparisons, not two
indexOf can't find NaN but includes can:
NaN vs NaN | +0 vs -0 | |||
|---|---|---|---|---|
==, != | ||||
===, !==, indexOf, switch cases | ||||
includes, Map and Set keys | ||||
Object.is |
Fixing the settings bug
value is always a string, so limit == 0 matches "0", "" and " ". Switching to === makes it match nothing, because a string is never === a number. The fix isn't a different operator. It's converting once at the edge and deciding what an empty field means:
// limit comes from an <input>'s value, so it is always a stringfunction describeLimit(limit) { if (limit == 0) return "Unlimited"; // "0", "" and " " all match return `${limit} downloads`;}console.log(describeLimit("0")); // Unlimitedconsole.log(describeLimit("")); // Unlimited, but the field is emptyconsole.log(describeLimit("5")); // 5 downloads// convert once at the edge, then compare like with likefunction parseLimit(text) { if (text.trim() === "") return null; // empty means "not set" const n = Number(text); return Number.isInteger(n) && n >= 0 ? n : null;}function describeLimit(limit) { if (limit === null) return "Not set"; if (limit === 0) return "Unlimited"; return `${limit} downloads`;}console.log(describeLimit(parseLimit("0"))); // Unlimitedconsole.log(describeLimit(parseLimit(""))); // Not setconsole.log(describeLimit(parseLimit("5"))); // 5 downloads=== in the second version isn't doing anything clever. It works because both sides are already numbers or null, so there is no conversion left to surprise anyone.
How to apply it in your project
Convert at the boundary Turn form values, query parameters and storage values into the type you mean, with Number()or an explicit check for"", right where they enter your code.Default to === Once types are settled, ===says exactly what you mean. Keep== nullonly where it clearly means "missing".Use the right tool for NaN and zeros Use Number.isNaN(x)to detectNaN,includesinstead ofindexOfwhen an array may holdNaN, andObject.iswhen the sign of zero matters.Compare objects by their fields Neither operator looks inside objects. Compare the field that defines identity, like an id, or write a small function that compares the fields you care about.
Key takeaways
==and===behave identically when both operands have the same type; they only differ on mixed types.==converts in specific steps:nullandundefinedonly match each other, booleans and strings become numbers, objects become primitives.===isn't just "value and type":NaNnever equals itself,+0equals-0, and objects compare by identity.Object.is,includes,MapandSetuse their own sameness rules, soNaNand-0behave differently there.Fix comparisons by converting inputs once at the edge; swapping the operator alone just moves the bug.
التعليقات (0)