== vs === in js

发布时间 2023-04-27 12:18:43作者: ChuckLu

== vs === in js

In JavaScript, == and === are comparison operators that are used to compare two values. However, they have different behaviors and are used in different situations.

The == operator is known as the "loose equality" operator. When using ==, JavaScript will attempt to convert the operands to a common type before making the comparison. This means that operands of different types may be considered equal if they have the same "value" after being converted to a common type. For example, the following code will evaluate to true:

console.log(5 == "5"); // true

In this case, JavaScript will convert the string "5" to the number 5 before making the comparison. This behavior can be useful in some cases, but can also lead to unexpected results if not used carefully.

 

The === operator is known as the "strict equality" operator. When using ===, JavaScript will only consider the operands to be equal if they are of the same type and have the same value. For example, the following code will evaluate to false:

console.log(5 === "5"); // false

In general, it is recommended to use === in most cases, as it is more predictable and less error-prone than ==. However, there may be cases where == is more appropriate or necessary, such as when comparing values of different types that are known to have equivalent values after conversion.