When working with JavaScript, it’s important to understand the difference between strict equality and loose equality, as they can affect the outcome of your code. In this blog, we’ll discuss the differences between the two and provide some examples to help you understand.
- Loose Equality(==): Loose Equality checks whether the two operands are equal and returns a boolean result. It is called “loose” because it allows for type coercion, which means the values that are being compared don’t have to be the same data type. JavaScript attempts to convert the values to the same type and then compare the operands.
console.log(1 == “1”)In the above code, javaScript first converts the string “1” into a number and then compares the values. Hence, the expression result is true.
But sometimes, the loose Equality can provide some unexpected results:
console.log(1==true)In the above example, the boolean value is coerced to be number 1 and compares which result is true.
- Strict Equality (===): Strict Equality checks whether the two operands are equal, returning a boolean result. Unlike loose Equality it doesn’t convert the operand into the same data type, hence there is no coercion. When using strict equality, JavaScript will only return true, if both the values and the data type match.
console.log(1==”1″)
console.log(1===1)In the above example, Javascript doesn’t convert the string into a number hence its result is false. It returns true when both the values and data type match.
Conclusion: In summary, loose equality allows for type coercion and can sometimes lead to unexpected results, while strict equality doesn’t allow for type coercion and is more predictable. As a beginner, it’s important to understand the difference between the two and use them appropriately in your code.
Source: hashnode.com