Functions of the equals operators (== and ===)

The two equals operators supported by JavaScript can cause a little bit of confusion when working with them.

When using ==, values can be considered equal even when they are of different types. This can be confusing even for a senior JavaScript developer. Let's analyze how == works using the following table:

Type(x)

Type(y)

Result

null

undefined

true

undefined

null

true

Number

String

x == toNumber(y)

String

Number

toNumber(x) == y

Boolean

Any

toNumber(x) == y

Any

Boolean

x == toNumber(y)

String or Number

Object

x == toPrimitive(y)

Object

String or number

toPrimitive(x) == y

 

If x and y are of the same type, then JavaScript ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.