Equality Operators: Interview Question Series
I am bringing it back to JavaScript basics! There is one question that I have come across in about 90% of my interviews. That question is ‘what is the difference between a double equal and a triple equal in JavaScript?’.
Let’s talk about it!
Loose Equality Operator ( == , !=)
This operator will return true if two values are equal. Before it makes the comparison, it converts the values to the same type. This means that if you are comparing a number and a string it will first convert the string to a number and then compare the values.
Example:
24 == 24
// true24 == '24'
//true
!= acts the same way, except it will return true if two values are not equal
Example :
24 != '24'
// false24 != 25
// true24 != '25'
//true
Strict Equality Operator ( === , !==)
The strict equality operator will not complete type conversion before comparing the two values. This means that if you try to compare an integer and a string, it will return false. Let’s check out some examples.
Using === :
22 === 22
//true 22 === '22'
// false
The strict inequality operates the same way except it will return true if two values are not equal. It will also not complete type conversation before evaluating.
22 !== 22
//false 22 !== 20
// true22 !== '22'
// true
Every time I explain the difference between these two equality comparisons, I give a simple example. This is helpful as I believe (or hope) it shows I understand the concept even though I may have gotten nervous in the interview and forgotten certain keywords or stumbled on the definition.
The example I always use is:
1 === '1'
// false 1 == 1
//true
The interview process continues!