Interview question
What is type coercion in JavaScript? Explain == vs ===. JavaScript में type coercion क्या है? == बनाम === समझाएं।
Answer
Type coercion is the automatic conversion of values from one type to another. The == operator performs coercion, while === does not.
// Type coercion with ==
console.log(5 == '5'); // true (string coerced to number)
console.log(5 === '5'); // false (different types)
console.log(true == 1); // true (boolean coerced to number)
console.log(true === 1); // false
console.log(null == undefined); // true (special case)
console.log(null === undefined); // false
console.log([] == 0); // true (array coerced to number)
console.log([] === 0); // false| Operator | Name | Coercion? | Recommendation |
|---|---|---|---|
| == | Loose equality | Yes, unpredictable | Avoid |
| === | Strict equality | No, type-safe | Always use |
Interview tip: Always use === in production code. Explain some quirks like [] == 0 being true but [] == false also being true - these show why == is dangerous.
Type coercion automatically एक type से दूसरी type में values को convert करता है। == operator coercion करता है, === नहीं।
console.log(5 == '5'); // true (string को number में convert)
console.log(5 === '5'); // false (अलग types)
console.log(true == 1); // true
console.log(true === 1); // false
console.log(null == undefined); // true (special case)
console.log(null === undefined); // false
console.log([] == 0); // true
console.log([] === 0); // false| Operator | नाम | Coercion? | Recommendation |
|---|---|---|---|
| == | Loose equality | हाँ, unpredictable | Avoid करें |
| === | Strict equality | नहीं, type-safe | हमेशा use करें |
इंटरव्यू टिप: Production में हमेशा === use करें। Quirks बताएं जैसे [] == 0 true है पर [] == false भी true है - यह दिखाता है == क्यों dangerous है।
Was this answer clear?