Learn the basics of JavaScript Function Parameters.

A function in JavaScript can accept one or more parameters. Let’s look at some examples:

const doSomething = () => {
  //do something
}

const doSomethingElse = (foo) => {
  //do something
}

const doSomethingElseAgain = (foo, bar) => {
  //do something
}

Starting from ES6/ES2015, functions can have default values for their parameters. Here’s an example:

const doSomething = (foo = 1, bar = 'hey') => {
  //do something
}

This allows you to call the function without specifying all the parameters:

doSomething(3);
doSomething();

In ES2018, trailing commas for parameters were introduced. This feature helps reduce bugs due to missing commas when rearranging parameters:

const doSomething = (foo = 1, bar = 'hey',) => {
  //do something
}

doSomething(2, 'ho!');

It is also okay to call your functions with a trailing comma after the last parameter:

doSomething(2, 'ho!',);

You can also wrap all your arguments in an array and use the spread operator when calling the function:

const doSomething = (foo = 1, bar = 'hey') => {
  //do something
}
const args = [2, 'ho!'];
doSomething(...args);

With many parameters, it can be difficult to remember their order. By using objects and destructuring, you can keep the parameter names:

const doSomething = ({ foo = 1, bar = 'hey' }) => {
  //do something
  console.log(foo); // 2
  console.log(bar); // 'ho!'
}
const args = { foo: 2, bar: 'ho!' };
doSomething(args);

Functions also support default parameters:

const foo = function(index = 0, testing = true) { /* ... */ }
foo();

Default parameter values were introduced in ES2015 and are widely implemented in modern browsers.

Here’s an example of a doSomething function that accepts param1:

const doSomething = (param1) => {

}

You can add a default value for param1 if the function is invoked without specifying a parameter:

const doSomething = (param1 = 'test') => {

}

This works for multiple parameters as well:

const doSomething = (param1 = 'test', param2 = 'test2') => {

}

What if you have a unique object with parameter values in it? In the past, if we had to pass an object of options to a function and have default values for those options if they were not defined, we had to add some code inside the function:

const colorize = (options) => {
  if (!options) {
    options = {}
  }

  const color = ('color' in options) ? options.color : 'yellow'
  // ...
}

With object destructuring, you can provide default values, which simplifies the code significantly:

const colorize = ({ color = 'yellow' }) => {
  // ...
}

If no object is passed when calling the colorize function, you can assign an empty object as the default:

const spin = ({ color = 'yellow' } = {}) => {
  // ...
}