== vs === in JavaScript: what's the difference?

By

Learn the difference between the == and === operators in JavaScript: === checks both type and value while == coerces types, so default to === in most cases.

~~~

In JavaScript you can use two different operators to check for object equality. They are == and ===.

They basically do the same thing, but there is a big difference between the two.

=== will check for equality of two values. JavaScript is dynamically typed. You still have some fundamental types which you must know about.

In particular we have 7 primitive types: string, number, bigint (ES2020), boolean, undefined, symbol (ES2015), and null. Then we have reference types (Array, Object, Function). I have a post on primitive types vs objects.

If two values are not of the same type, === will return false.

If they are of the same type, JavaScript will check for equality.

With reference types, this means the values need to reference the same object / array / function. Not one with the same values: the same one.

== is different because it will attempt to convert types to match.

This is why you get results like

false == '0'  //true
false === '0' //false
null == undefined //true
null === undefined  //false

In my experience, in 97% of the cases you’ll want to use ===, unless == provides exactly what you want. It has less drawbacks and edge cases.

The same goes for != and !==, which perform the same thing, but negated.

Always default to !==.

Object.is() is the other strict check: like ===, except it treats NaN as equal to NaN and 0 as different from -0. See also JavaScript equality operators.

If you want to see exactly how == converts types in any comparison, I built a free JS equality explorer where you can try these live.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: