This is very common question asked in JavaScript related interviews because generally everyone is used to of “==” but we should know the difference between “==” and “===” in JavaScript.
Since JavaScript support both strict equality and type-converting equality, it’s important to know which operator is used for which operation.
The double equal “==” is an auto type conversion and used to compare by the value only whether it is a variable or a constant.
The three equal “===” is a not auto-type conversion and used to compare by it’s type and value both. If type is not the same but value is same then also it returns false.
The real examples are as follows:
1 | 0==false // true, because false is equivalent of 0 |
1 | 0===false // false, because both operands are of different type |
1 | 2=="2" // true, <span id="IL_AD1" class="IL_AD">auto</span> type <span id="IL_AD4" class="IL_AD">conversion</span>, string converted into number |
1 | 2==="2" // false, since both operands are not of same type |
1 | if(1 == "1") //will return true due to compare by value |
1 | if(1==="1") // will return false due to "1" is string type and 1 is number //type so type is different while value is same |
but if we cast or convert the type of “1” then we can compare and it will return type as below
1 | if(1 === parseInt("1")) // return true due to type conversion |
That’s all about difference between “==” and “===” in JavaScript, you should always use strict equality operator i.e. === and avoid using == operator even if you need type coercion, instead convert the type by yourself to make it more readable.