Type Conversion
JavaScript is dynamically typed, meaning variables can change types. Sometimes you need to convert between types explicitly.
Implicit Conversion (Coercion) JavaScript automatically converts types in certain operations:
- String + Number = String (concatenation)
- Number + Boolean = Number (true = 1, false = 0)
- Comparisons with == perform type coercion
Explicit Conversion You can manually convert types using built-in functions:
To String:
- String(value)
- value.toString()
- Template literals:
${value}
To Number:
- Number(value)
- parseInt(string) - for integers
- parseFloat(string) - for decimals
- Unary plus: +value
To Boolean:
- Boolean(value)
- Double negation: !!value
Truthy and Falsy Values: Falsy values (convert to false): 0, "", null, undefined, NaN, false Everything else is truthy (converts to true)
Code Examples
// String concatenation wins
console.log("5" + 3); // "53" (string)
console.log("5" + true); // "5true" (string)
// Math operations convert to numbers
console.log("5" - 3); // 2 (number)
console.log("5" * 2); // 10 (number)
console.log("10" / 2); // 5 (number)
// Boolean in math
console.log(5 + true); // 6 (true = 1)
console.log(5 + false); // 5 (false = 0)
// Comparison coercion (use === to avoid)
console.log("5" == 5); // true (type coercion)
console.log("5" === 5); // false (strict equality)
console.log(null == undefined); // true
console.log(null === undefined); // falseAlways use === (strict equality) to avoid unexpected type coercion. Only use == when you intentionally want type coercion.
// To String
let num = 42;
console.log(String(num)); // "42"
console.log(num.toString()); // "42"
console.log(`${num}`); // "42"
// To Number
let str = "123";
console.log(Number(str)); // 123
console.log(parseInt(str)); // 123
console.log(parseFloat("3.14")); // 3.14
console.log(+"99"); // 99 (unary plus)
// Invalid conversions
console.log(Number("hello")); // NaN
console.log(parseInt("10px")); // 10 (stops at non-digit)
// To Boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
console.log(!!null); // false
console.log(!!{}); // true (empty object is truthy!)Explicit conversion makes your intent clear and helps prevent bugs. Always validate user input before converting.
Quick Quiz
1. What is the result of '5' + 3 in JavaScript?
2. Which value is NOT falsy in JavaScript?
Was this lesson helpful?