Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Type conversion

A value often arrives in the wrong type: an age from a form field comes as a string, a number has to be shown as text. Turning a value of one type into another is called type conversion.

String to number

The Number() function turns a string into a number. After that you can calculate with it:

console.log(Number('42') + 1); // 43

If the string cannot be read as a number, the result is NaN — "not a number":

console.log(Number('forty')); // NaN

parseInt and parseFloat

Number() is strict: any extra characters give NaN. The parseInt() and parseFloat() functions read a number from the start of the string and stop at the first character that does not fit:

console.log(parseInt('12px'));     // 12
console.log(parseFloat('3.5 kg')); // 3.5
console.log(Number('12px'));       // NaN

parseInt() returns a whole number, while parseFloat() keeps the fractional part. They are handy when a number comes with units attached.

Number to string

The String() function turns any value into a string. The toString() method gives the same result:

console.log(String(42) + 1); // 421

Now + joins instead of adding: '42' + 1 gives '421'.

Boolean value

The Boolean() function answers whether a value counts as true. Only six values are false: false, 0, the empty string '', null, undefined and NaN. Everything else is true:

console.log(Boolean(0));      // false
console.log(Boolean('0'));    // true
console.log(Boolean('text')); // true

The string '0' is true: it is not empty, there is a character inside.

Implicit conversion

Sometimes JavaScript converts types by itself, without being asked — this is implicit conversion. The -, * and / operators turn strings into numbers, while + with a string turns a number into a string:

console.log('6' * '2'); // 12
console.log('6' + 2);   // 62

Code like this is easy to misread, so it is better to convert types explicitly with Number() and String().

Common mistake

An empty string and a string of spaces become zero, not NaN. So an empty form field silently turns into the number 0:

console.log(Number(''));  // 0
console.log(Number(' ')); // 0

If an empty value should count as an error, first check that the string is not empty, and only then convert it.

Thanks for reading!

Donate to the site — we work hard for you.