Skip to content

2.6 Type Conversions

Bunlong VAN edited this page Feb 15, 2018 · 4 revisions

Most of the time, operators and functions automatically convert a value to the right type. That’s called “type conversion”.

For example, alert automatically converts any value to a string to show it. Mathematical operations convert values to numbers.

There are also cases when we need to explicitly convert a value to put things right.


Not talking about objects yet

In this chapter we don’t cover objects yet. Here we study primitives first. Later, after we learn objects, we’ll see how object conversion works in the chapter Object to primitive conversion.


ToString

String conversion happens when we need the string form of a value.

For example, alert(value) does it to show the value.

We can also use a call String(value) function for that:

let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string "true"
alert(typeof value); // string

String conversion is mostly obvious. A false becomes "false", null becomes "null" etc.

ToNumber

Numeric conversion happens in mathematical functions and expressions automatically.

For example, when division / is applied to non-numbers:

alert( "6" / "2" ); // 3, strings are converted to numbers

We can use a Number(value) function to explicitly convert a value:

let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number

Explicit conversion is usually required when we read a value from a string-based source like a text form, but we expect a number to be entered.

If the string is not a valid number, the result of such conversion is NaN, for instance:

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed

Numeric conversion rules:

Clone this wiki locally