Curriculum

Curriculum

Reject Invalid Inputs Explicitly in JavaScript

Scenario

Test canBook in JavaScript with -1, "2", and 1.5.

Selected choicePick a choice below
Result—
JavaScript
export function canBook(freeSeats) {
  if (!Number.isInteger(freeSeats) || freeSeats < 0) {
    throw new RangeError("INVALID_FREE_SEATS");
  }
  return freeSeats > 0;
}

Try it yourself

Compare how Number.isInteger catches every non-integer trap cleanly.

Reveal the explanation
  1. canBook(-1)

    Throws RangeError("INVALID_FREE_SEATS").

  2. canBook("2")

    Number.isInteger("2") is false -> throws RangeError("INVALID_FREE_SEATS").

  3. canBook(1.5)

    Number.isInteger(1.5) is false -> throws RangeError("INVALID_FREE_SEATS").

JavaScript’s loose comparison ("2" > 0 -> true) hides bad types. Guarding with Number.isInteger keeps JavaScript aligned with Python and Go.

Review first
Download shared test cases

Your turn

Write an assert.throws test in Node checking that canBook("2") throws /INVALID_FREE_SEATS/.

Common mistake Calling canBook("2") directly inside assert.throws(canBook("2")) instead of wrapping it in an arrow function () => canBook("2").

Check your work

assert.throws(() => canBook("2"), /INVALID_FREE_SEATS/).

Quick check

What does Number.isInteger("2") return in JavaScript?
Show the answer and reasoning

Correct answer false (it does not coerce strings into numbers)

Number.isInteger strictly checks both number type and integer value with zero coercion.