and the object type:
undefined, but there’s no point in casting from/to them)
For example, you might want to convert:
- a number to a string
- a string to a number
- a string to a boolean
- a boolean to a string
…and so on.
Here are the techniques you can use to convert from one type to another. I cover the most common cases.
Converting to strings
In general converting from anything to a string is usually a matter of calling the
String() global function.
Casting from number to string
Use the String global function, or the Number type
String(10) //"10" (10).toString() //"10"
Casting from boolean to string
Use the String global function, or the Boolean type
String(true) //"true" true.toString() //"true" String(false) //"false" false.toString() //"false"
Casting from date to string
Use the String global function, or the Date type
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
We can do this by using the
Number("1") //1 Number("0") //0
Strings are trimmed before being converted to numbers:
Number(" 1 ") //1
passing an empty string defaults to 0:
and to have work with decimals you use a dot:
If a string contains invalid characters, it will generate a
Math.floor(), the unary
Casting from boolean to number
Just as we did for string, passing a boolean to
Number() will return either 0 or 1:
Number(true) //1 Number(false) //0
Casting from date to number
If you pass a Date object to
Number(), it will return the date timestamp, which is the best date to number conversion you can get.
Special cases with number
Number(null) //0 Number(undefined) //NaN Number(NaN) //NaN
Converting to booleans
Any value can be converted to boolean passing it to
All values will resolve to
Boolean(false) //false Boolean(0) //false Boolean(NaN) //false Boolean("") //false Boolean(null) //false Boolean(undefined) //false
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X