You will get the distinction between == and === in JavaScript after reading this blog.
We come across many situations in daily life where we need to compare two items. In javascript, the comparison is performed using the equality operators i.e
"==" called loose equality
"===" called strict equality
The main difference between the == and === operators in javascript is that the == operator converts the operands' types before comparing them, whereas the === operator compares the operands' values as well as their data types. Both == and === will return a boolean value.
Consider the example below to understand it better,
Here in this example, we are comparing two images
Consider Image 1 has a Value: hogwarts and Type: png and
Image 2 has Value: hogwarts and Type: jpeg
We can observe that the value of both images is the same but the types of the images are different. Hence we get the below result.
The "==" Operator
When we use "==" to compare, it performs coercion before the comparison. Hence it compares only the value between the operands and not the type. If the values are the same after the coercion, then it will return true else it will return a false value.
What is coercion?
Coercion is the automatic conversion of values from one data type to another before doing the comparison.
The "===" Operator
When we use "===" to compare, it will check that both should be the same type and value. To return true, both must be of the same type and value. Otherwise, the result is false.
Here are a few examples where "==" and "===" produce different results:
//Comparing a number and a string
console.log(6 == "6"); //true - string is converted to number
console.log(6 == "6"); //false - number is not equal to string
//Comparing number and a boolean
console.log(0 == False); //true, because false is equivalent of 0
console.log(0 == False); //false, because both are of different type
//Comparing null or undefined
console.log(null == undefined); // true
console.log(null === undefined); // false
//Comparing NaN (Not a Number) with any number or NaN itself will be false because NaN (Not a Number) is not equal to anything, including NaN.
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
Conclusion
It is always better to use === as it helps to maintain data type integrity throughout your code.
References
MDN Docs