Basically, type coercion is a concept in which JavaScript auto-converts types in some operations.
Example:
"5" + 1 // "51" β number converted to string
"5" - 1 // 4 β string converted to number
true + 1 // 2
null + 1 // 1
undefined + 1 // NaN
π Two Main Types of Coercion
- Implicit Coercion Happens automatically when JavaScript converts one data type to another during operations.
Example:
console.log(1 + '2'); // "12" (number 1 converted to string)
console.log('5' * 2); // 10 (string '5' converted to number)
console.log(5 == '5'); // true (string '5' converted to number for comparison)
2.Explicit Coercion
Happens when you intentionally convert a value using built-in functions or operators.
Example:
Number('123'); // 123
String(123); // "123"
Boolean(0); // false
βοΈ Common Conversion Rules
- String + Number β String (concatenation)
- String * Number / String - Number β Number (if string is numeric)
- == (loose equality) allows type coercion
- === (strict equality) does not allow type coercion (compares value & type)
π Common Type Coercion Table
Expression What Happens Internally Result / Type
1 + '2' Number 1 β String "1" then "1" + "2" "12" (string)
'5' * 2 String '5' β Number 5 then 5 * 2 10 (number)
'10' - 3 String '10' β Number 10 then 10 - 3 7 (number)
true + 1 Boolean true β Number 1 then 1 + 1 2 (number)
false + 10 Boolean false β Number 0 then 0 + 10 10 (number)
null + 1 null β Number 0 then 0 + 1 1 (number)
undefined + 1 undefined β NaN NaN (number)
[] + [] Both arrays β Strings "" + "" "" (string)
π‘ Best Practices
Prefer explicit coercion to avoid unexpected results.
Use === instead of == for comparisons unless you intentionally want coercion.
Top comments (0)