JavaScript · Chapter 38 of 55

JavaScript Type Conversion

JavaScript often converts values from one type to another automatically, called type coercion — for example, `'5' + 1` produces `'51'` because + triggers string concatenation.

You can also convert types explicitly using functions like `String()`, `Number()`, and `Boolean()`, which is safer and clearer than relying on implicit coercion.

Implicit coercion

`+` with a string operand converts everything to strings, while `-`, `*`, `/` try to convert operands to numbers. This can cause surprising results like `'5' - 1` being `4` but `'5' + 1` being `'51'`.

Explicit conversion

`Number('42')` gives 42, `String(42)` gives '42', and `Boolean(1)` gives true — always predictable and easy to read.

Example 1 (javascript)
console.log("5" + 1);
console.log("5" - 1);
Output
51
4

+ concatenates when a string is involved; - coerces to numbers.

Example 2 (javascript)
console.log(Number("42"));
console.log(String(42));
console.log(Boolean(""));
Output
42
42
false

Explicit conversion functions make the intended type change obvious.

Key points

  • + concatenates strings; other math operators coerce to numbers.
  • Number(), String(), Boolean() perform explicit conversion.
  • Implicit coercion can cause confusing bugs — be cautious with +.
  • Number('abc') returns NaN, since 'abc' isn't numeric.
💡 Note: When mixing types in an expression, convert explicitly first to avoid relying on JavaScript's coercion rules.

📝 Quick Quiz

1. What does `'5' + 1` return?

2. What does `'5' - 1` return?

3. Which function explicitly converts to a number?