Saying no, clearly
A function asked to divide by zero, or to withdraw more money than there is, should refuse loudly instead of returning nonsense. You can create errors yourself with throw.
throw and catch
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Not enough money");
}
return balance - amount;
}
try {
console.log(withdraw(500, 200));
console.log(withdraw(500, 900));
console.log("never reached");
} catch (err) {
console.log("Problem:", err.message);
} finally {
console.log("Receipt printed");
}There are built-in error types too: TypeError, RangeError… throw new RangeError("Too big") tells the reader what kind of problem it is.