How does JavaScript handle type coercion?
Asked on Jul 19, 2024
Answer
JavaScript handles type coercion by automatically converting values from one type to another when performing operations that require different types. This can happen in both implicit and explicit contexts.
// Implicit coercion
console.log('5' + 3); // "53"
console.log('5' - 3); // 2
// Explicit coercion
console.log(Number('5') + 3); // 8
console.log(String(5) + '3'); // "53"
Additional Comment:
✅ Answered with JavaScript best practices.- Implicit coercion occurs when JavaScript automatically converts types, like concatenating a string with a number.
- Explicit coercion is when you manually convert types using functions like Number() or String().
- Be cautious with implicit coercion as it can lead to unexpected results.
- Always prefer explicit coercion for clarity and to avoid bugs.
Recommended Links:
← Back to All Questions