How to set default parameter values in JavaScript

Learn how to add default parameter values to JavaScript functions

Default parameter values have been introducedES6Released in 2015 and widely implemented in modern browsers.

This is andoSomethingAccepted featuresparam1.

const doSomething = (param1) => {

}

We can add default values forparam1If the function is called without specifying the parameters:

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

}

Of course, this also applies to more parameters:

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

}

What if you have a unique object with parameter values?

Once upon a time, if we had to pass an option object to a function so that the default value of these options (if one of them is not defined) has a default value, we must add some code inside the function:

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

const color = (‘color’ in options) ? options.color : ‘yellow’ … }

By destructuring, you can provide default values, which greatly simplifies the code:

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

If no object is passed when calling our programcolorizeFunction, similarly, we can allocate an empty object by default:

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

Download mine for freeJavaScript beginner's manual


More js tutorials: