Skip to main content
eLearner.app
Module 2 · Lesson 4 of 48/32 in the course~8 min
Module lessons (4/4)

Type conversions

All the time you need to transform the type of a value: the value of an HTML input arrives as a string even if it represents a number, an API returns strings to format, you need to log an object as text. JS offers three families of conversions: explicit, dedicated parsers, and (to be avoided) implicit ones.

Explicit conversions

These are the clearest and should be your default:

JS
Number('42'); // 42
Number('3.14'); // 3.14
Number(''); // 0     ← careful
Number('  10 '); // 10     (spaces are ignored)
Number('ciao'); // NaN    ← does not represent a number

String(42); // '42'
String(true); // 'true'
String(null); // 'null'
String(undefined); // 'undefined'

Boolean(1); // true
Boolean(0); // false
Boolean(''); // false
Boolean('abc'); // true

parseInt and parseFloat: tolerant parsers

Unlike Number(...), parseInt and parseFloat ignore the non-numeric tail of the string: they stop at the first invalid character.

JS
Number('42px'); // NaN
parseInt('42px'); // 42
parseFloat('3.14em'); // 3.14
parseInt('   12 anni'); // 12
parseInt('ciao12'); // NaN  ← must start with digits

toFixed to format numbers as strings

Seen briefly in the previous lesson: rounds to N decimals and returns a string.

JS
(3.14159).toFixed(2); // '3.14'
(1).toFixed(2); // '1.00'

To convert it back to a number use the Number(...) prefix or the unary +:

JS
Number((3.14159).toFixed(2)); // 3.14
+(3.14159).toFixed(2); // 3.14

NaN: the value that bites

NaN ("Not a Number") is produced by numeric operations that fail:

JS
Number('ciao'); // NaN
0 / 0; // NaN
parseInt('xxx'); // NaN

Characteristics:

  • it has type 'number' (yes, a "non-number" is a number)
  • it is not equal to itself: NaN === NaN is false
  • to test it use the function Number.isNaN(x)
JS
const x = Number('ciao');
x === NaN; // false (!)
Number.isNaN(x); // true

Try it

Exercise#js.m2.l4.e1
Attempts: 0Loading…

Given the string '128.95 EUR', extract the (decimal) number and round it to the nearest integer, returning it as a number. Expected: 129.

Loading editor…
Show hint

parseFloat ignores 'EUR'; .toFixed(0) rounds to an integer as a string; Number(...) converts back to a number.

Solution available after 3 attempts

Review exercise

Exercise#js.m2.l4.e2
Attempts: 0Loading…

Given `n = Number('non un numero')`, write a single expression that evaluates to true if the result is NaN.

Loading editor…
Show hint

Use Number.isNaN, not n === NaN: NaN is not equal to itself.

Solution available after 3 attempts