How to Use Default Values for JavaScript Arguments

Setting default values for JavaScript arguments used to be pretty annoying. You had to perform tasks such as checking for undefined values and then setting the value(s) inside the code block. However, with modern JS versions, you can set the defaults inside of the function declaration itself, like this:

function invoiceGenerator(client, state = 'AZ', amount) {
  console.log(`Company: ${client}`);
  console.log(`State: ${state}`);
  console.log(`Amount: $${amount}`);
}
invoiceGenerator('Google', undefined, 500);

 

Which will result in the output:

"Company: Google"

"State: AZ"

"Amount: $500"

 

Please note how I had to pass in undefined when I called the function as one of the function arguments. This is because JavaScript doesn't magically know how the function argument data is mapped. It simply follows the same order as in the function declaration.