JS: == vs. ===

Published on: October 25, 2014

Tags: js and interview-questions

What is the difference between == and ===?

Triple equals checks for type and equality.

Double equals only checks for equality.

What? How can you check for equality without checking type?

JS uses type coercion to check for equality without checking type. Here’s an example:

1
2
3
4
1 == "1" // returns true

// what's really happening is:
1 === Number("1") // returns true

So when we do 1 == "1" JS does type coercion to check for equality. That means it makes both sides of the same type (in this case Number). From there it checks for equality with type.

I had problems with another example, so we'll walk through that one too.

1
'0' == false //returns true

Here’s how the logic goes (from Mozilla via stackoverflow):

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Note: you can read the full spec here, it’s smaller than I expected.

So, in our example, one of the operands is a boolean. So then we convert both operands to numbers:

1
2
3
Number('0') == Number(false)
// goes to...
0 == 0

From here we can test for equality with type since both operands are numbers.

TL;DR

Use ===. Always.

Resources


comments powered by Disqus