Learn the fundamentals of JavaScript type conversions

Even though JavaScript is a loosely typed language, there may arise situations where you need to convert a value from one type to another.

In JavaScript, we have primitive types like numbers, strings, booleans, and symbols, along with the object type. However, converting from or to null and undefined is not necessary.

Here are some common conversion scenarios and techniques to achieve them:

Converting to Strings

Converting anything to a string can generally be done by calling the toString() method on the value or using the String() global function.

Converting from a number to a string

You can use the String() global function or the toString() method of the Number type:

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

Converting from a boolean to a string

You can use the String() global function or the toString() method of the Boolean type:

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

Converting from a date to a string

You can use the String() global function or the toString() method of 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 strings

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

Converting to Numbers

Converting from a string to a number

You can achieve this by using the Number() global function, which acts as a constructor. When passed a string, JavaScript figures out how to convert it to a number:

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

Strings are trimmed before being converted:

Number(" 1 "); //1

Passing an empty string defaults to 0:

Number(""); //0

To work with decimal numbers, use a dot:

Number("12.2");

If a string contains invalid characters, it will generate NaN.

For more detailed information on converting strings to numbers, refer to how to convert a string to a number in JavaScript. There are other methods like parseInt(), parseFloat(), Math.floor(), and the unary + operator.

Converting from a boolean to a number

Just like converting a string, passing a boolean to Number() will return either 0 or 1:

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

Converting from a date to a number

If you pass a Date object to Number(), it will return the date timestamp, which is the most accurate conversion from date to number.

Special cases with numbers

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

Converting to Booleans

Any value can be converted to a boolean by passing it to Boolean(). All values will resolve to true except for:

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