Values and variables

JavaScript Type Conversions (casting)

Learn how to convert values between types in JavaScript, casting numbers, strings and booleans using helpers like String(), Number() and the toString() method.

JavaScript is loosely typed, but you still convert values between types all the time.

Primitive types:

Object type:

(null and undefined exist too, but you rarely cast to or from them.)

Common jobs:

  • a number to a string
  • a string to a number
  • a string to a boolean
  • a boolean to a string

Converting to strings

Call toString() on a value, or pass it to String():

Casting from number to string

String(10) //"10"
(10).toString() //"10"

Casting from boolean to string

String(true) //"true"
true.toString() //"true"
String(false) //"false"
false.toString() //"false"

Casting from date to string

String(new Date('2019-01-22'))
//"Tue Jan 22 2019 01:00:00 GMT+0100 (Central European Standard Time)"

(new Date('2019-01-22')).toString()
//"Tue Jan 22 2019 01:00:00 GMT+0100 (Central European Standard Time)"

Special cases with string

String(null) //"null"
String(undefined) //"undefined"
String(NaN) //"NaN"

Converting to numbers

Casting from string to number

Number() parses a string into a number:

Number("1") //1
Number("0") //0

Strings are trimmed first:

Number(" 1 ") //1

An empty string becomes 0:

Number("") //0

Decimals use a dot:

Number("12.2")

Invalid characters produce NaN.

For more options see how to convert a string to a number in JavaScript. You can also use parseInt(), parseFloat(), Math.floor(), or the unary + operator.

Casting from boolean to number

Number(true) //1
Number(false) //0

Casting from date to number

Number(date) returns the timestamp in milliseconds.

Special cases with number

Number(null) //0
Number(undefined) //NaN
Number(NaN) //NaN

Converting to booleans

Boolean(value) converts any value. These six become false:

Boolean(false) //false
Boolean(0) //false
Boolean(NaN) //false
Boolean("") //false
Boolean(null) //false
Boolean(undefined) //false

Everything else is true, including '0' and empty arrays.

Implicit conversion also happens in comparisons and template literals. That is why Number() and String() are worth practicing explicitly: you learn what the language will do anyway.

When parsing user input, validate after conversion. Number('12abc') is NaN, and NaN is falsy but not equal to anything, including itself.

Try Number('42px'), String({}), and Boolean('') in the console. Note which results are useful and which signal bad input.

Lesson completed