Double (==) equal and Triple (===) equal sign - how it works on JavaScript | a brief explanation!

 In JavaScript, we may come across double equal (==) and triple equal (===) sign while checking the equality of two variables' values.

But why two different operators are there for the same operation of equality check? What do they actually mean? You will find the answers in this blog.



1. How == (double equal) works

Double equal does the loose equality check. It checks the value equality only. It converts the type of the variables to match each other. Some common examples of double equal (==) check of two variables x and y are given below in tabular form -

x
y
x==y
undefined
undefined / null
true
undefined
true / false / NaN / 0 / 17 / 'string'
false
null
true / false / NaN / 0 / 12 / 'string'
false
null
null / undefined
true
NaN
any-value
false
new String("mukitul")
"mukitul"
true
{property:'value'}
{property:'value'}
false

2. How === (triple equal) works
Triple equal does the strict equality check. It checks the equality of the value and the variable's type. It doesn't forcefully convert the type of variables. Some common examples of double equal (===) check of two variables x and y are given below in tabular form -
x
y
x===y
undefined
undefined
true
undefined
null / true / false / NaN / 0 / 17 / 'string'
false
null
true / false / NaN / 0 / 12 / 'string'
false
null
null
true
NaN
any-value
false
new String("mukitul")
"mukitul"
false
{property:'value'}
{property:'value'}
false

3. When to use == or ===
Triple equal (===) operator ensures two operands (or variables) are of the same value and type when it returns true or returns false. Double equal (==) doesn't check type equality, it only considers the value of two operands.
Suppose a scenario where the response from an API call gives both "true" and true, in this case, we can check the response in JavaScript/client-side using double equal (==). But we should keep in mind that, it is highly recommended to use triple equal (===) when checking the equality of two operands unless there is any extreme situation occurs like the above scenario.

So, if we don't have any strong use case for using double equal (==) then we must use triple equal (===) which will save us from many potential bugs.

Have a good day!

Comments