JavaScript Typecasting: Converting Data Types
Learn how to convert data types in JavaScript
In JavaScript, although it is a loosely typed language, there may be instances where you need to convert values from one type to another.
JavaScript has these primitive types:
- Number
- String
- Boolean
- Symbol
and the object type:
- Object
(plus null and undefined, but there’s no point in casting from/to them)
Let’s explore different techniques for converting from one type to another. We’ll cover the most common scenarios.
Converting to Strings
In general, converting from any type to a string in JavaScript is usually done by calling the toString()
method on a value or using the String()
global function.
Casting from a Number to a String
You can use the String()
global function or the toString()
method on the Number type:
1 | String(10) //"10" |
Casting from a Boolean to a String
You can use the String()
global function or the toString()
method on the Boolean type:
1 | String(true) //"true" |
Casting from a Date to a String
You can use the String()
global function or the toString()
method on the Date type:
1 | String(new Date('2019-01-22')) |
Special Cases with Strings
1 | String(null) //"null" |
Converting to Numbers
Casting from a String to a Number
You can use the Number()
global function to convert a string to a number. JavaScript will handle the conversion automatically:
1 | Number("1") //1 |
Strings are trimmed before being converted to numbers:
1 | Number(" 1 ") //1 |
An empty string defaults to 0:
1 | Number("") //0 |
To work with decimals, use a dot notation:
1 | Number("12.2") |
If a string contains invalid characters, it will generate NaN
.
To learn more about converting strings to numbers in JavaScript, check out our guide on how to convert a string to a number in JavaScript. There are other methods available, such as parseInt()
, parseFloat()
, Math.floor()
, and the unary +
operator.
Casting from a Boolean to a Number
Similar to casting to a string, passing a boolean to Number()
will return either 0 or 1:
1 | Number(true) //1 |
Casting from a Date to a Number
If you pass a Date object to Number()
, it will return the date timestamp, which is the best way to convert a date to a number.
Special Cases with Numbers
1 | Number(null) //0 |
Converting to Booleans
You can convert any value to a boolean by passing it to the Boolean()
function.
All values will resolve to true
except for:
1 | Boolean(false) //false |
tags: [“type casting”, “JavaScript”, “data types”, “Number”, “String”, “Boolean”, “Symbol”, “Object”]