Last updated: August 27, 2026.
A function groups reusable behavior, accepts parameters, and can return a value.
function calculateTotal(price, quantity = 1) {
if (!Number.isFinite(price) || !Number.isInteger(quantity) || quantity < 0) {
throw new TypeError("Invalid price or quantity");
}
return price * quantity;
}
console.log(calculateTotal(12.5, 3));Variables declared inside a function are local to it. Keep functions focused and make inputs and return values explicit. See the MDN functions guide.