Both "==" and "===" are used for equality comparison in Javascript. To understand the difference between them we first need to know what is Type coercion.
Type coercion:
Type coercion in JS refers to the process of converting a value from one data type to another. This can happen implicitly( automatically by the Javascript engine) or explicitly(using built-in methods or operators).
For example, when you use a `+` operator with a string and a number, Javascript will implicitly convert the number to a string before concatenating the two values. So "1"+2 would result in the string "12"
.
The Difference:
In Javascript, the `==` operator is used for loose equality comparison, meaning it checks whether the values are equal without checking their data types and it performs type coercion if necessary. For example, 1="1" would be true because the two values are considered equal even though one is a number and the other is a string.
On the other hand, the ===
operator is used for strict equality comparisons, meaning it checks whether the values are equal and also checks their data types.
For example, 1==="1"
would be false because the two values are not considered equal due to their different data types.
In general, it's recommended to use the ===
operator for equality comparison in Javascript to avoid unexpected results that may arise from type coercion.