I’m trying to understand how default parameters work in Javascript. From my knowledge so far, it should be fairly straightforward – if I have a function like so:
function calculateTotal(prices = [], tip = 0, tax = 0) {
return prices.reduce((a, b) => a + b, 0) + tip + tax
}
running
console.log(calculateTotal(tip = 4))
should print out 4, but it prints out Uncaught TypeError: prices.reduce is not a function and NaN, because apparently prices is initialized to undefined as opposed to the default value of []. However, if I do
console.log(calculateTotal([], tip = 4))
it prints 4. Is there something I’m missing about using arrays as default parameters?
>Solution :
calculateTotal(tip = 4) doesn’t mean what you think it means.
It means:
- Evaluate the expression
tip = 4which:- Creates an implicit global
tip(this is an error in strict mode, which you should be using) - Assigns the value
4to that global - Evaluates as the value
4
- Creates an implicit global
- Assign the result of that expression as the first argument to the
calculateTotalfunction- i.e.
calculateFunction(4)where the second and third parameters are given their default values from the function definition.
- i.e.
JavaScript doesn’t have any feature that allows assignment to parameters by name, only position.
The usual way to handle that is by passing a single argument, an object, and using destructuring to turn it into variables.
const example = ({ foo = 1, bar = 2, baz = 3} = {}) => {
console.log(foo, bar, baz);
};
example();
example({ bar: 17 });