CodeBlanks Logo Icon CodeBlanks

Handling error cases

JavaScript course · Beginner · Lesson 28/133

Add guards for division by zero and invalid operator.

Error cases: validation with isNaN

What happens if the user enters letters instead of a number? parseFloat("hello") returns NaN — 'Not a Number'. Math with NaN again gives NaN, so we must check the result.

The isNaN(value) function tells whether a value is not a number: it returns true if it isn't, false if it is. We use it inside an if condition.

To check both numbers we combine the checks with the || (or) operator: if (isNaN(first) || isNaN(second)). If invalid, we put an error message in result.

Flow control with if/else

If validation fails, the computation should not run. We enforce this with if/else: the if condition catches invalid input, and the else block runs the switch when valid.

This way the switch only runs when both numbers are valid. In the error case, result is already set to an error message and the switch is skipped.

In both paths the result is written to the result variable, so a single console.log at the end covers every case.

Exercise Add input validation with isNaN

The existing code computes with switch but doesn't check for invalid input. Wrap the switch in an if/else. First validate both numbers with if (isNaN(first) || isNaN(second)); if invalid, assign an error message to result. If valid, the existing switch should run inside the else block. A final console.log should print the result.

Show example solution
// The user's first value
const firstInput = "25";
const operator = "+";
const secondInput = "4";
const first = parseFloat(firstInput);
const second = parseFloat(secondInput);

let result;

if (isNaN(first) || isNaN(second)) {
  result = "Error: please enter a valid number";
} else {
  switch (operator) {
    case "+":
      result = first + second;
      break;
    case "-":
      result = first - second;
      break;
    case "*":
      result = first * second;
      break;
    case "/":
      result = first / second;
      break;
    default:
      result = "Unknown operation";
  }
}

console.log("Result: " + result);

Test yourself

  1. Which of these returns NaN?

    parseFloat("hello")
    • parseFloat("42")
    • Number("3.14")
    • parseFloat("100 meters")
    • parseFloat("hello")
    Show answer

    parseFloat("hello") — Correct. 'hello' cannot be converted, so NaN is returned.

  2. Complete the if condition

    ____
      result = "Error: please enter a valid number";
    }
    Show answer
    if (isNaN(first) || isNaN(second)) {
      result = "Error: please enter a valid number";
    }
  3. Match the validation concepts

    isNaN
    Checks if a value is not a number
    NaN
    Result of an invalid number operation
    parseFloat
    Converts a string to a decimal number
    ||
    Logical OR

All lessons in Beginner