Type Conversion & Coercion in JavaScript


In JavaScript, values can be converted from one data type to another. This is called type conversion. Sometimes JavaScript does it automatically (called type coercion), and other times you do it manually.


1. Type Conversion (Explicit)

This is when you manually convert a value from one type to another.


Convert to String

String(123);        // "123"
(123).toString();   // "123"

Convert to Number

Number("123");      // 123
parseInt("50px");   // 50
parseFloat("3.14"); // 3.14

Convert to Boolean

Boolean(1);         // true
Boolean(0);         // false
Boolean("hello");   // true
Boolean("");        // false

2. Type Coercion (Implicit)

JavaScript automatically converts types when needed — sometimes in unexpected ways!


Examples

"5" + 1     // "51"  → number is converted to string
"5" - 1     // 4     → string is converted to number
true + 1    // 2     → true becomes 1
false + 1   // 1     → false becomes 0
null + 1    // 1     → null becomes 0
undefined + 1 // NaN → undefined becomes NaN

This is why it’s important to understand coercion — it can lead to bugs if you're not careful!


Equality and Coercion

"5" == 5    // true  → values are coerced before comparison
"5" === 5   // false → strict comparison (no coercion)

Always prefer === and !== to avoid coercion surprises.