乐闻世界logo
搜索文章和话题

What is the difference between `==` and `===`? When to use `==` for equality?

2024年6月24日 16:43

In JavaScript, both == and === are comparison operators, but they handle value comparison differently.

=== is known as the strict equality operator, which compares both the type and value of two operands. If the data types differ, it directly returns false without performing type coercion. Only when both the data type and value match does === return true.

Example:

javascript
3 === 3 // true, because both type and value are identical 3 === '3' // false, because one is a number type and the other is a string type

== is referred to as loose equality operator, which performs type coercion during comparison. If the types differ, it converts them to the same type before comparing their values.

Example:

javascript
3 == 3 // true, as both type and value are identical 3 == '3' // true, even though types differ (one is a number, the other is a string), // because '3' is converted to the number 3 before comparison

Generally, in coding, it is recommended to use === to avoid unexpected results due to type coercion. This is also endorsed by code quality tools and best practices. However, in specific cases where you understand the type coercion mechanism and wish to leverage it for code simplification, == can be used. For example:

javascript
// Here we know that x could be either the numeric value 0 or the string "0", and both are considered equivalent function checkZero(x) { return x == 0; } checkZero(0); // true checkZero("0"); // true, because "0" is converted to the number 0 before comparison

In the above code, using == accepts both the string '0' and the number 0 as equivalent. If using ===, you would need additional code to handle type checking and conversion. However, unless there is a very clear justification, it is generally recommended to use === as it makes code behavior more predictable and explicit.

标签:JavaScript前端