JavaScript Type Conversion
8 April 2025 | Category: JavaScript
In JavaScript, type conversion refers to changing a value from one data type to another. It happens in two ways:
- Implicit Conversion (Type Coercion) – done automatically by JavaScript
- Explicit Conversion – done manually by the developer
📌 1. Implicit Type Conversion (Type Coercion)
JavaScript automatically converts types when needed.
🧪 Example:
let result = "5" + 2;
console.log(result); // "52" (number 2 converted to string)
let result2 = "5" - 2;
console.log(result2); // 3 (string "5" converted to number)
⚠️ Rules:
+
operator converts numbers to strings if one operand is a string- Other arithmetic operators (
-
,*
,/
) convert strings to numbers
📌 2. Explicit Type Conversion
You control the conversion using built-in functions.
🔢 Convert to Number
Use Number()
, parseInt()
, or parseFloat()
.
✅ Examples:
Number("123"); // 123
Number("abc"); // NaN
parseInt("10.5"); // 10
parseFloat("10.5"); // 10.5
🧠 Special Cases:
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number(undefined); // NaN
🔡 Convert to String
Use String()
or .toString()
.
✅ Examples:
String(123); // "123"
(123).toString(); // "123"
String(true); // "true"
String(null); // "null"
🔁 Convert to Boolean
Use Boolean()
to convert a value to true
or false
.
✅ Examples:
Boolean(0); // false
Boolean(""); // false
Boolean(null); // false
Boolean(undefined);// false
Boolean(NaN); // false
Boolean("hello"); // true
Boolean(1); // true
📋 Truthy and Falsy Values
🔴 Falsy Values (evaluated as false):
0
""
(empty string)null
undefined
NaN
false
🟢 Everything else is truthy
🔍 Example: Type Conversion in Action
let x = "10";
let y = 5;
let sum = Number(x) + y;
console.log(sum); // 15 (x is converted to number)
let result = x + y;
console.log(result); // "105" (y is converted to string)
✅ Summary Table
Conversion | Method(s) | Example |
---|---|---|
To Number | Number() , parseInt() | Number("10") → 10 |
To String | String() , .toString() | String(5) → "5" |
To Boolean | Boolean() | Boolean(0) → false |
Auto Conversion | Implicit via operators | "5" + 2 → "52" |
🧠 Best Practices
- Use explicit conversion to avoid unexpected results.
- Be careful with
==
vs===
(the former allows type coercion).