Tech Hacks

JavaScript Basics: Difference between == & === (with examples)

JavaScript has two sets of equality operators: === and ==. They mostly work exactly the same ie, if the operands are of the same type and have the same value, then === produces true & so does ==. But if the operands are of different types, then === produces false & == says true. The simplest reason is that == is also a type converter.

Here are some examples of === & == in action:

true == 1 // true
true === 1 // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false

== is also notoriously inconsistent. See the below examples:

'' == '0' // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

Best practice is to avoid == and use === consistently in your code.