How == and === are different in JavaScript

By FoxLearn 12/18/2024 8:24:22 AM   26
In JavaScript, == and === are both comparison operators, but they behave differently.

== is the equality operator in JavaScript. It checks if two values are equal, but it performs type conversion if the values are of different types.

For example:

console.log(5 == '5');   // true (string '5' is converted to number 5)
console.log(0 == false); // true (false is converted to 0)
console.log(null == undefined); // true (considered equal in non-strict comparison)

=== is the strict equality operator in JavaScript. It checks if two values are equal and of the same type, without performing any type conversion.

For example:

console.log(5 === '5');   // false (different types: number vs string)
console.log(0 === false); // false (different types: number vs boolean)
console.log(null === undefined); // false (different types)

In summary, use == when you want to check for equality regardless of type, and use === when you want to check for both value and type equality. It is generally recommended to use === to avoid unexpected results caused by type conversion.