Loading lessons...
Type Conversion
JavaScript can convert values between types, both automatically and by hand.
Convert to string
js
### String(123); // "123"
(123).toString(); // "123"
### String(true); // "true"
Convert to number
js
### Number("123"); // 123
### Number("3.14"); // 3.14
### Number(""); // 0
### Number("abc"); // NaN
Convert to boolean
js
### Boolean(1); // true
### Boolean(0); // false
### Boolean(""); // false
### Boolean("hi"); // true
Implicit conversion
JavaScript converts types automatically in many situations:
js
"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:
js
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.