Data type conversion means changing a value from one type to another.
👉 There are two types of conversion:
- Implicit Conversion (Type Coercion)
- Explicit Conversion (Type Casting)
🔹 1. Implicit Conversion (Automatic)
JavaScript automatically converts types when needed.
✅ Example 1: String + Number
let result = "5" + 2;
console.log(result); // "52"
👉 Number 2 is converted to string.
✅ Example 2: Number – String
let result = "5" - 2;
console.log(result); // 3
👉 String "5" is converted to number.
✅ Example 3: Boolean Conversion
let result = true + 1;
console.log(result); // 2
👉 true → 1, false → 0
✅ Example 4: Null Conversion
let result = null + 5;
console.log(result); // 5
👉 null behaves like 0
⚠️ Strange Cases
console.log("5" * "2"); // 10
console.log("hello" * 2); // NaN
👉 "hello" cannot be converted → NaN (Not a Number)
🔹 2. Explicit Conversion (Manual)
You manually convert using JavaScript functions.
✅ Convert to Number
Using Number()
Number("123"); // 123
Number("abc"); // NaN
Number(true); // 1
Number(false); // 0
Using parseInt() and parseFloat()
parseInt("10.5"); // 10
parseFloat("10.5"); // 10.5
✅ Convert to String
Using String()
String(123); // "123"
String(true); // "true"
Using .toString()
let num = 100;
num.toString(); // "100"
✅ Convert to Boolean
Using Boolean()
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("Hello"); // true
Boolean(null); // false
Boolean(undefined);// false
🔹 Truthy vs Falsy Values
❌ Falsy Values:
0""(empty string)nullundefinedNaNfalse
✅ Truthy Values:
Everything else is true
Boolean("Hi"); // true
Boolean(100); // true
🔹 Comparison with Type Coercion
== (Loose Equality)
console.log("5" == 5); // true
👉 Converts types before comparison
=== (Strict Equality)
console.log("5" === 5); // false
👉 No conversion → safer
🧠 Quick Summary
| Conversion Type | Example | Result |
|---|---|---|
| Implicit | "5" + 2 | "52" |
| Implicit | "5" - 2 | 3 |
| Explicit | Number("10") | 10 |
| Explicit | String(10) | "10" |
| Explicit | Boolean(0) | false |