You can also create errors yourself, using throw. This is useful when someone uses your function in a way that doesn't make sense, and you want to stop them immediately with a clear message:
function withdraw(balance, amount) {
if (amount <= 0) {
throw new Error("Withdrawal amount must be positive.");
}
if (amount > balance) {
throw new Error(`Insufficient funds: you have ${balance}, but tried to withdraw ${amount}.`);
}
return balance - amount;
}
console.log(withdraw(100, 30));
try {
withdraw(100, 500);
} catch (error) {
console.log("Transaction failed:", error.message);
}
withdraw(100, -5);
It prints
70 Transaction failed: Insufficient funds: you have 100, but tried to withdraw 500. Uncaught Error: Withdrawal amount must be positive.
new Error("message") creates an error object with your message, and throw launches it. It works just like JavaScript's built-in errors: if nobody catches it, the program stops and shows your message.
Why would you want to cause an error? Because a clear error right away is much better than a mysterious bug later. If withdraw(100, -5) quietly returned 105, someone would have just gained money by withdrawing, and nobody would notice until the bank went bankrupt. Throwing an error makes problems loud and obvious. Loud bugs are easy to fix. Quiet bugs are the dangerous ones.