== vs === in JavaScript

In JavaScript, == and === are comparison operators used to compare two values. However, they differ in how they handle type conversion.

== (Equality Operator)

The == operator checks for equality but performs type coercion if the types of the operands are different. This means that it tries to convert the operands to the same type before making the comparison.

Examples

console.log(5 == '5');          // true (number and string are coerced to the same type)
console.log(0 == false);        // true (0 is coerced to false)
console.log(null == undefined); // true (special case)
console.log('' == false);       // true (empty string is coerced to false)

=== (Strict Equality Operator)

The === operator checks for equality without performing type coercion. This means that if the operands are of different types, the result is false without attempting to convert them.

Examples

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)
console.log('' === false);      // false (different types: string vs boolean)
console.log(5 === 5);           // true (same type and value)

In Table

Sure, here's a table that highlights the key differences between == and === in JavaScript:

Comparison== (Equality Operator)=== (Strict Equality Operator)
Type CoercionYes, performs type coercion.No, does not perform type coercion.
Type ComparisonConverts operands to the same type before comparing.Compares both value and type.
Example: 5 and '5'5 == '5' evaluates to true.5 === '5' evaluates to false.
Example: 0 and false0 == false evaluates to true.0 === false evaluates to false.
Example: null and undefinednull == undefined evaluates to true.null === undefined evaluates to false.
Example: '' and false'' == false evaluates to true.'' === false evaluates to false.
Example: true values5 == 5 evaluates to true.5 === 5 evaluates to true.
Typical Use CasesUsed when type conversion is acceptable or desired.Used when exact match without type conversion is required.

Summary

  • Use == when you want to allow type conversion and just care about the values being equivalent after conversion.

  • Use === when you want to ensure both the value and the type are exactly the same. This is generally recommended to avoid unexpected results due to type coercion.