Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass an empty array as a default function parameter in Javascript?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Evaluate the expression tip = 4 which:
    • Creates an implicit global tip (this is an error in strict mode, which you should be using)
    • Assigns the value 4 to that global
    • Evaluates as the value 4
  2. Assign the result of that expression as the first argument to the calculateTotal function
    • i.e. calculateFunction(4) where the second and third parameters are given their default values from the function definition.

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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading