Difference between == & === Javascript
1. "==" (Loose Equality)
- Performs Type Coercion: If the types of the operands are different, JavaScript attempts to convert them to the same type before making the comparison.
- Drawback: Can lead to unexpected results due to type coercion, especially with different data types.
- Example:
console.log(5 == '5'); // Output: true (string '5' is converted to number 5)
console.log(false == 0); // Output: true (false is coerced to 0)
2. "===" (Strict Equality)
- No type Coercion: It checks both the value & the type. If the types are different, it immediately return
false.
- Benefit: Provides more predictable & safer comparisons by requiring both value & type to match.
- Example:
console.log(5 === '5'); // Output: false (different types: number and string)
console.log(false === 0); // Output: false (different types: boolean and number)