The difference between == and === in JavaScript is not a matter of personal style. It decides whether your comparison converts the types before it compares anything. The === operator compares values without any conversion, while the == operator applies a set of conversion rules first. Understanding those rules is the difference between fixing a comparison bug in ten minutes and guessing at it for an entire afternoon.
The previous lesson in this module covered "Arithmetic and Assignment Operators", and the next lesson in this module is about "The Ternary Operator and Short-Circuiting".
What is the difference between == and ===?
=== is the strict equality operator. Two values are equal under it only when they have the same type and the same value. == is the loose one. If the two types are different, it converts one of them first and then compares them.
console.log('1 == 1 and 1 === 1:', 1 == 1, 1 === 1);
console.log('1 == "1" and 1 === "1":', 1 == '1', 1 === '1');
console.log('0 == false and 0 === false:', 0 == false, 0 === false);
console.log('"" == false and "" === false:', '' == false, '' === false);
console.log('null == undefined:', null == undefined, '| null === undefined:', null === undefined);
console.log('NaN == NaN and NaN === NaN:', NaN == NaN, NaN === NaN);
console.log('0 === -0:', 0 === -0);
console.log('{} == {} and {} === {}:', {} == {}, {} === {});
Read that output as a list of surprises. The number 1 and the string '1' are loosely equal but not strictly equal. Zero and false are loosely equal. The empty string and false are loosely equal. null and undefined are loosely equal but not strictly equal. And two separate object literals are never equal, whether you use the loose rule or the strict one, because each literal is its own distinct object.
What exactly does == convert?
The rules are specific, and they explain almost every loose comparison that you will meet.
console.log('"5" == 5:', '5' == 5);
console.log('"5" === 5:', '5' === 5);
console.log('"5" + 5:', '5' + 5); // "55", because + joins text
console.log('"5" - 5:', '5' - 5); // 0, because - makes numbers
console.log('true == 1:', true == 1);
console.log('true == "1":', true == '1');
console.log('[] == false:', [] == false);
console.log('[1] == 1:', [1] == 1);
Here are the rules in plain words. If both sides have the same type, then == behaves exactly like ===. If one side is null and the other is undefined, then they are equal. In every other case, the engine converts one side to the type of the other side and compares them again.
The last two lines are where it becomes strange. false is converted into 0. An empty array is converted into an empty string, and an empty string is then converted into 0. An array with one element is converted into the text form of that element, so [1] becomes '1', and then '1' becomes 1. Every one of those steps is a documented rule, but the chain is long enough that relying on it is a bad idea.
Why does null == undefined return true?
Because == has one special case for those two values, and === does not. The two values are genuinely different from each other. One means "deliberately empty", and the other means "no value was provided". The loose operator still treats them as interchangeable.
console.log('null == undefined:', null == undefined);
console.log('null === undefined:', null === undefined);
console.log('null == 0:', null == 0);
console.log('undefined == 0:', undefined == 0);
console.log('null == false:', null == false);
console.log('null > 0:', null > 0);
Notice that null is only loosely equal to undefined. It is not loosely equal to 0, and it is not loosely equal to false. That special case is narrow, and it is deliberate.
If you want to test for "no value" and you mean both of them, then write the check out in full instead of relying on the conversion. Use value === null || value === undefined, or use the shorter value == null if you are comfortable with exactly one loose comparison in your whole codebase. Many teams ban == completely and use ?? for the same job.
What about NaN and negative zero?
NaN is the only value that is not equal to itself, under either operator. It means "this is not a number", and it appears when arithmetic cannot produce a number at all. Dividing 0 / 0 does it, and so does Math.sqrt(-1), and so does converting the text 'hello' with Number().
console.log('NaN === NaN:', NaN === NaN);
console.log('NaN == NaN:', NaN == NaN);
console.log('Number.isNaN(NaN):', Number.isNaN(NaN));
console.log('0 === -0:', 0 === -0);
console.log('Object.is(0, -0):', Object.is(0, -0));
Negative zero deserves a moment of your attention. It is a real thing in IEEE 754, and it comes out of arithmetic such as -1 * 0. The === operator considers it equal to zero. It hardly ever matters, but when it does, such as in a physics calculation or a direction check, you need Object.is.
There is a related detail that shows up when you search arrays. The includes method treats NaN as equal to NaN, but the indexOf method does not.
console.log('[NaN].indexOf(NaN):', [NaN].indexOf(NaN)); // -1
console.log('[NaN].includes(NaN):', [NaN].includes(NaN)); // true
What is Object.is for?
Object.is(a, b) is a third way to compare two values, and it arrived with the other ES2015 improvements. It behaves like ===, except that it tells NaN apart from everything else and it treats 0 and -0 as different values.
console.log('Object.is(1, 1):', Object.is(1, 1));
console.log('Object.is(NaN, NaN):', Object.is(NaN, NaN));
console.log('Object.is(0, -0):', Object.is(0, -0));
console.log('Object.is("a", "a"):', Object.is('a', 'a'));
console.log('Object.is({}, {}):', Object.is({}, {}));
Use Object.is when you need the mathematically precise answer, and use === everywhere else. It is not more correct in general. It is more precise about a smaller set of cases. The one place where it is clearly the right tool is a NaN check, because Object.is(x, NaN) says yes while x === NaN always says no.
So which operator should I use?
Use ===, almost every time. It compares what you think it compares. The exceptions are narrow enough to list.
- Use
===for every value comparison, including strings and numbers. - Use
== nullonly when you deliberately want to match bothnullandundefined, and only when your style guide allows it. - Use
Number.isNaN(value)instead ofvalue === NaNwhen you test forNaN. - Use
Object.iswhen you need to tell0and-0apart, or when you compareNaNvalues. - Remember that
switchuses===inside it, so aswitchon the number 2 will not match the case'2'.
The real danger of == is not that it is wrong. The danger is that it is right often enough to survive a code review. A comparison that converts '5' into a number, when you meant to catch a string that came back from an API, will not fail in your tests. It will fail in production, on the one request that returns a string where you expected a number.
The equality rules in one page
===compares the type and the value.==compares them after it has converted one side.null == undefinedistrue, andnull === undefinedisfalse.NaNis not equal to itself under either operator, so useNumber.isNaN.- Objects and arrays are compared by identity. Two literals are never equal, but the same reference always is.
0and-0are equal under===, and they are not equal underObject.is.- A loose comparison with an empty array walks through string and number conversions, so do not rely on it.
Try it yourself: write a function isSameId(a, b) that decides whether two values stand for the same identifier, given that one of them may arrive as a number from a database while the other arrives as a string from a query string. Test it with isSameId(42, '42'), isSameId(42, 42), and isSameId(null, undefined). Then write a second version that refuses to convert anything and returns false for anything except an exact match. Then decide which of the two you would rather debug at three in the morning.