Reject Invalid Inputs Explicitly in JavaScript
Scenario
Test canBook in JavaScript with -1, "2", and 1.5.
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.
| Case | Result |
|---|---|
| canBook(-1) | Select a choice above to see what happens. |
| canBook("2") | Select a choice above to see what happens. |
| canBook(1.5) | Select a choice above to see what happens. |
Reveal the explanation
- canBook(-1)
Throws RangeError("INVALID_FREE_SEATS").
- canBook("2")
Number.isInteger("2") is false -> throws RangeError("INVALID_FREE_SEATS").
- 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.
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
This browser could not save your progress. Changes last until you leave the page.