Beginner LevelJavaScript & TypeScript
What is the difference between == (loose equality) and === (strict equality)?
❓ Interview Prompt: Explain type coercion with == versus strict comparison with ===.
== (Loose Equality / Abstract Equality):
Performs type coercion before comparing. Converts operands to the same type, leading to unexpected results:
•
0 == '' → true (both coerced to 0)•
null == undefined → true (special rule)•
'1' == 1 → true (string converted to number)=== (Strict Equality):
Compares value AND type without coercion:
•
0 === '' → false (number vs string)•
null === undefined → false (different types)•
'1' === 1 → falseBest Practice:
Always use === and !==. The only valid == use case is value == null (checks both null and undefined).
Code Implementation Example
javascript
// ❌ Loose equality surprises
console.log(0 == ''); // true
console.log(0 == '0'); // true
console.log('' == '0'); // false (!)
console.log(false == '0'); // true
console.log(null == undefined); // true
// ✅ Strict equality (predictable)
console.log(0 === ''); // false
console.log(0 === '0'); // false
console.log(null === undefined); // false
// ✅ Only valid == use: null check
if (value == null) { /* value is null OR undefined */ }💡Loose equality coercion surprises vs strict equality predictability.
🎯 Interview Key Takeaway
Always use === for comparisons. Use == null as the only exception to check both null and undefined.
#Equality#Coercion#Comparison#Beginner
Back to all JavaScript & TypeScript Questions→