Type conversion transforms a value from one data type to another. It occurs either explicitly (intentional conversion via functions like String(), Number(), Boolean()) or implicitly (automatic coercion by the engine during arithmetic/logical operations).
flowchart TD
Conversion["Type Conversion"] --> Explicit["Explicit Casting (Intentional: Number('5'), String(10))"]
Conversion --> Implicit["Implicit Coercion (Engine Automatic)"]
Implicit --> PlusStr["String + Anything -> String Concatenation ('5' + 2 = '52')"]
Implicit --> MinusNum["String - Number -> Numeric Coercion ('5' - 2 = 3)"]
Implicit --> BoolCond["if(val) -> Boolean Coercion"]
| Target Type | Explicit Conversion Function | Example Input | Output |
|---|---|---|---|
| Number | Number(val) |
"42" / "" / false |
42 / 0 / 0 |
| String | String(val) |
100 / null / true |
"100" / "null" / "true" |
| Boolean | Boolean(val) |
0 / "Hello" / {} |
false / true / true |
| Integer | parseInt(val, 10) |
"42.9px" |
42 |
// Demonstrating Implicit Coercion vs Explicit Casting
// 1. Implicit Coercion Triggers
console.log("--- Implicit Coercion Output ---");
console.log(`"5" + 3: ${"5" + 3}`); // "53" (String concatenation trigger)
console.log(`"5" - 3: ${"5" - 3}`); // 2 (Numeric subtraction trigger)
console.log(`"5" * "2": ${"5" * "2"}`); // 10
console.log(`true + 1: ${true + 1}`); // 2 (true converted to 1)
console.log(`false + 1: ${false + 1}`); // 1 (false converted to 0)
// 2. Safe Explicit Casting
console.log("
--- Safe Explicit Casting ---");
const userFormInput = "150.50";
const parsedNumber = Number(userFormInput);
console.log(`Explicit Number: ${parsedNumber} (Type: ${typeof parsedNumber})`);
const count = 42;
const explicitString = String(count);
console.log(`Explicit String: "${explicitString}" (Type: ${typeof explicitString})`);
// 3. Object to Primitive Coercion (valueOf / toString)
const customObj = {
valueOf() { return 10; }
};
console.log(`Custom Object + 5: ${customObj + 5}`); // 15
Number(str), String(val), and Boolean(val) explicitly so code intentions are obvious to readers.+ Coercion Hacks: Avoid writing +str to convert strings to numbers. Prefer Number(str) or parseFloat(str) for clarity.string primitives from the DOM. Convert explicitly before math operations.What are the explicit results of Number(null), Number(undefined), String(null), and Boolean(null)?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.