Data Type Conversion in Javascript

javascript Aug 01, 2019

Converting between one data type and another is a very common task. Data that comes from user input or other systems often has to be converted. This section covers some of the more common data conversion techniques.

Converting to Numbers

It’s very common to want to convert strings to numbers. When you collect input from a user, it’s usually as a string, even if you’re collecting a numeric value from them. JavaScript offers a couple of methods to convert strings to numbers. The first is to use the Number object constructor

const numStr = "33.3"; 
const num = Number(numStr);   // this creates a number value, *not*                              // an instance of the Number object 

If the string can’t be converted to a number, NaN will be returned. The second approach is to use the built-in parseInt or parseFloat functions. These behave much the same as the Number constructor, with a couple of exceptions. With parseInt, you can specify a radix, which is the base with which you want to parse the number. For example, this allows you to specify base 16 to parse hexadecimal numbers. It is always recommended you specify a radix, even if it is 10 (the default). Both parseInt and parseFloat will discard everything they find past the number, allowing you to pass in messier input. Here are examples:

const a = parseInt("16 volts", 10);  // the " volts" is ignored, 16 is                                     // parsed in base 10 
const b = parseInt("3a", 16);        // parse hexadecimal 3a; result is 58 const c = parseFloat("15.5 kph");    // the " kph" is ignored; parseFloat                                     // always assumes base 10

A Date object can be converted to a number that represents the number of milliseconds since midnight, January 1, 1970, UTC, using its valueOf() method:

const d = new Date();         // current date 
const ts = d.valueOf();       // numeric value: milliseconds since                              // midnight, January 1, 1970 UTC 

Converting to String

All objects in JavaScript have a method toString(), which returns a string representation. In practice, the default implementation isn’t particularly useful. It works well for numbers, though it isn’t often necessary to convert a number to a string: that conversion usually happens automatically during string concatenation or interpolation. But if you ever do need to convert a number to a string value, the toString() method is what you want:

const n = 33.5; n;                      // 33.5 - a number 
const s = n.toString(); s;                      // "33.5" - a string 

Date objects implement a useful (if lengthy) toString() implementation, but most objects will simply return the string "[object Object]". Objects can be modified to return a more useful string representation, but that’s a topic for Chapter 9. Arrays, quite usefully, take each of their elements, convert them to strings, and then join those strings with commas:

const arr = [1, true, "hello"]; 
arr.toString();                 // "1,true,hello

Converting to Boolean

we’ll learn about JavaScript’s idea of “truthy” and “falsy,” which is a way of coercing all values to true or false, so we won’t go into all those details here. But we will see that we can convert any value to a boolean by using the “not” operator (!) twice. Using it once converts the value to a boolean, but the opposite of what you want; using it again converts it to what you expect. As with numeric conversion, you

can also use the Boolean constructor (again, without the new keyword) to achieve the same result:

const n = 0;              // "falsy" value 
const b1 = !!n;           // false 
const b2 = Boolean(n);    // false 

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning