Difference Between == and === in JavaScript

In JavaScript, the == and === operators are used for comparison, but they behave differently due to their respective comparison types.

== (Equality Operator)

The == operator checks for equality of values after performing type coercion if the operands have different types. Type coercion is the process of converting one data type to another for comparison. It converts operands to the same type before evaluating the equality.

console.log(1 == '1'); // Output: true

In this case, the number 1 is converted to a string '1' through type coercion, and the comparison evaluates to true since both operands have the same value.

However, == can lead to unexpected results in certain situations due to its type coercion behavior.

console.log(0 == false); // Output: true console.log(null == undefined); // Output: true console.log('' == false); // Output: true

In these cases, the operands have different data types, but the == operator performs type coercion and evaluates the comparison as true.

=== (Strict Equality Operator)

The === operator, also known as the strict equality operator, checks for both equality of values and data types. It does not perform type coercion.

console.log(1 === '1'); // Output: false

In this case, the === operator evaluates to false because the operands have different data types: number and string.

The strict equality operator is more predictable and generally recommended because it avoids unexpected type coercion. It ensures that both value and data type must match for the comparison to evaluate to true.

console.log(0 === false); // Output: false console.log(null === undefined); // Output: false console.log('' === false); // Output: false

In these cases, the === operator evaluates to false since the operands have different data types.


javascript comparison operators

Conclusion

The == performs type coercion before comparison and is less strict, while === does not perform type coercion and is more strict, considering both value and data type for comparison. It is generally recommended to use === (strict equality) as it leads to more predictable and less error-prone code.