== vs. ===

Posted by Olena on March 15, 2019

Javascript implements dynamic typing and typecasting. We can coerse one type to another explicitly or let Javascript do it for us.

const    x=54;
const  explisit=String(x);  // explisit==="54"
const  implisit=x+"";           // implisit==="54"

In the second example we rely on Javascript behavior to coerse a number to a string.

There are two ways to compare values in Javascript:

  • == - loose equality operator
  • === - strict equality operator

The main difference beetween two operators is that == coerses the types, while === requires types to be equivalent. The rule of thumb is to never use == because you have to know exacly how every single thing coerses. Also, every single person who reads your code should have this knowledge as well. And some of them are mght be somewhat surprising.

2 == '42'
// => true
 
true == 1
// => true
 
'0' == false
// => true
 
null == undefined
// => true
 
' ' == 0
// => true

The full coersing chart looks like this here.

While == operator’s behavior sometimes looks strange and makes little sense, === operator behaves totally logical and acurate as one could expect.

42 === 42
// => true
 
42 === '42'
// => false
 
true === 1
// => false
 
'0' === false
// => false
 
null === undefined
// => false
 
' ' === 0
// => false

In conclusion, always use ===. It helps to avoid inaccuracy and to increase readability of your code.