CodeBlanks Logo Icon CodeBlanks

Common conversion pitfalls

JavaScript course · Beginner · Lesson 98/133

Learn common number-conversion mistakes and how to avoid them.

The NaN trap

When Number() receives a string it cannot convert, it returns NaN. For example Number("abc") gives NaN.

The trap is this: NaN is a number type, and when it enters a math operation it keeps the result NaN. NaN + 5 is still NaN. Worse, NaN === NaN returns false. That is why you always check for NaN with Number.isNaN(). This way bad input does not spread silently.

Empty string becomes zero

Another common trap for counters: Number("") returns 0. So an empty user input can be confused with 0.

To prevent this you first look at whether the input is empty or invalid. The rule is: catch empty input with if (input === ""); catch invalid input with else if (Number.isNaN(Number(input))); in the remaining case use the real number. This order prevents unexpected zeros.

Exercise Safe number parser

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

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

Exercise Test three input kinds

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

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

console.log(safeParse("42"));
console.log(safeParse("abc"));
console.log(safeParse(""));

Test yourself

  1. What does Number("abc") return?

    console.log(Number("abc"));
    • NaN
    • 0
    • undefined
    • "abc"
    Show answer

    NaN — Correct. Number() returns NaN because it cannot convert the string.

  2. Add the NaN check

    let n = Number(input);
    if (____(n)) {
      console.log("Invalid");
    }
    Show answer
    let n = Number(input);
    if (Number.isNaN(n)) {
      console.log("Invalid");
    }
  3. Match the conversion result

    Number("abc")
    NaN (letters)
    Number("")
    0 (empty)
    Number("42")
    42 (number)
    Number("42px")
    NaN (mixed)

All lessons in Beginner