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
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.
- Massive amounts of documentation on stackoverflow (I love the community!)
- Very clear examples on stackoverflow
- Interactive display of truthiness by @tjmcewan (if that link is dead, you can check out the code)
- My question