What is the difference between triple equals, ===, and double equals, ==, in JavaScript?

Question

What is the difference between triple equals, ===, and double equals, ==, in JavaScript?

Answer

While these are both comparison equality operators, the triple equals, ===, is what’s called a strict equality operator while the double equals is an equality operator.

The strict equality operator will compare both the value and type of the operands (the values on the left/right sides of the operator). If the value is the same but the type is not, the equality will evaluate to false.
For example:
4 === "4" //will evaluate to 'false' as the left operand is of type 'number' while right operand is of type 'string'

However, the following code block, which uses the equality operator instead, will evaluate to true. This is because the operands of the equality operator will be converted to the same type (if they are not already) before the values of the operands are compared.
4 == "4" //will evaluate to 'true'

9 Likes

Which of the different types will it change the operands to if you use the equality operator rather than the strict equality operator? Can you give an example of a situation where it would be best to use the equality operator rather than the strict version? I’m having a much harder time grasping how js works.

Take for example,

false == 0    =>  true
false === 0   =>  false

0 != false    =>  false
0 !== false   =>  true

The above demonstrates coercion of a number to a boolean, and a boolean to a number only when the operation is loose type matching, and not when it is strict.

Following we coerce string to number, and number to string…

1 == '1'    =>  true
'1' == 1    =>  true

1 === '1'   =>  false

So far we’ve been using literals, but expressions, too resolve to a value of some data type which can in turn be coerced.

12 Likes

Gotcha, I remember you explaining this in another thread. It was just over my head at the time.

3 Likes