CodeBlanks Logo Icon CodeBlanks

Summary - Type conversion

JavaScript course · Beginner · Lesson 99/133

Write a function that safely converts user input to numbers using type conversion.

Summary - Type conversion

In this group you saw the two faces of type conversion. With explicit conversion you use the String(), Number() and Boolean() functions. With implicit coercion, structures like +, - and if change the type for you.

You also learned the difference between == and ===, the six falsy values and the NaN trap of Number(). Now you will write a function that combines all of this: it will safely convert a user-entered string to a number and catch invalid input.

Exercise Safe toNumber function

Define a function called toNumber. It should take an input parameter. Inside, convert to a number with let n = Number(input). Check for NaN with if (Number.isNaN(n)); if it is NaN, return null. Otherwise, finally return n to give the number back.

Show example solution
function toNumber(input) {
  let n = Number(input);
  if (Number.isNaN(n)) {
    return null;
  }
  return n;
}

Exercise Call toNumber with four values

The toNumber function below is defined. Now call it with four values and print the result: console.log(toNumber("42")), console.log(toNumber("abc")), console.log(toNumber("")) and console.log(toNumber("0")). Put each call on its own line.

Show example solution
function toNumber(input) {
  let n = Number(input);
  if (Number.isNaN(n)) {
    return null;
  }
  return n;
}

console.log(toNumber("42"));
console.log(toNumber("abc"));
console.log(toNumber(""));
console.log(toNumber("0"));

Test yourself

  1. Match the concepts

    String()
    Explicit
    + "5"
    Implicit
    ===
    Strict equality
    0
    Falsy value
  2. Which is an explicit type conversion?

    • "5" - 0
    • +"5"
    • Number("5")
    • "5" + 3
    Show answer

    Number("5") — Correct. Number("5") explicitly converts to a number; the others are implicit coercion.

All lessons in Beginner