JavaScript Tutorial · JavaScript Basics · Lesson 12 of 44

JavaScript Type Conversion

Convert between strings, numbers and booleans — and avoid implicit coercion traps.

Explicit conversion

Convert values deliberately with String(), Number() and Boolean():

Example 1Try it yourself
console.log(String(123), typeof String(123));
console.log(Number("3.14"), Number(""), Number("12px"));
console.log(parseInt("12px"), parseFloat("1.5em"));
console.log(Boolean(1), Boolean(""));
console.log((255).toString(16), (5).toString(2));

Output

123 string
3.14 0 NaN
12 1.5
true false
ff 101

Number() is strict — the whole string must be a number. parseInt()/parseFloat() read as much as they can from the start.

Implicit coercion

Operators sometimes convert types for you. + with a string concatenates; other arithmetic operators convert to numbers:

Example 2Try it yourself
console.log("5" + 3);
console.log("5" - 3);
console.log("5" * "2");
console.log(true + 1);
console.log([] + []);
console.log([1, 2] + [3]);

Output

53
2
10
2

1,23

These rules are a classic interview topic — see the coercion output puzzle. In real code, convert explicitly and compare with ===.

Test yourself

What does "5" + 3 evaluate to?

  1. 8
  2. "53"
  3. NaN
  4. "8"
Show answer

Answer: "53"

With a string on either side, + concatenates, so 3 becomes "3".

Practice next