JS Type Conversion
JavaScript freely converts between types in expressions. Explicit conversion is preferable — the implicit kind is the source of half the language's bug stories.
Explicit conversions (recommended)
| To | Use |
|---|---|
| Number | Number(x), parseInt(x, 10), parseFloat(x), unary +x |
| String | String(x), x.toString(), template literal `${x}` |
| Boolean | Boolean(x), !!x |
| Integer | Math.trunc(x), x | 0 (32-bit), Math.floor / round / ceil |
Implicit conversions (gotchas)
JS
"" + 42 // "42" ← + with a string concatenates
"5" - 1 // 4 ← - forces numeric
true + 1 // 2 ← true → 1
null == 0 // false ← but null == undefined is true
[] + [] // "" ← arrays coerce to strings via join
[] + {} // "[object Object]"
{} + [] // 0 ← parsed as block + array (yes really)
Safe conversions
JS
// String → integer
const n = Number.parseInt(input.trim(), 10);
if (!Number.isFinite(n)) throw new Error("not a number");
// String → boolean (don't use Boolean("false") — that's true!)
const yes = ["1", "true", "yes", "on"].includes(value.toLowerCase());
// Force one type before comparing
const same = String(a) === String(b);
Tip: Always use
=== and !==. The coercion rules of == are a flowchart most senior devs can't recite from memory.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Type Conversion!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Coerce a string to a base-10 integer safely.
const n =
.parseInt(input, 10);
Six letters.
Discussion
Loading…