Lesson 88 +15 XP

Type Conversion

Type Conversion

JavaScript can convert values between types, both automatically and by hand.

Convert to string

String(123);     // "123"
(123).toString(); // "123"
String(true);    // "true"

Convert to number

Number("123");  // 123
Number("3.14"); // 3.14
Number("");     // 0
Number("abc");  // NaN

Convert to boolean

Boolean(1);    // true
Boolean(0);    // false
Boolean("");   // false
Boolean("hi"); // true

Implicit conversion

JavaScript converts types automatically in many situations:

"5" + 1; // "51"  (the + joins as strings)
"5" - 1; // 4     (the - forces numbers)

Why conversion matters

Forms give you strings. If you need numbers, convert them first:

let value = "10";
Number(value) + 5; // 15

TL;DR

  • String(), Number(), Boolean() convert explicitly.
  • The + operator joins strings.
  • - * / force numbers.
  • Always convert form input before math.