/

How to Set Default Parameter Values in JavaScript

How to Set Default Parameter Values in JavaScript

Learn how to add default parameter values to your JavaScript functions for improved flexibility and ease of use.

Default parameter values were introduced in ES6 in 2015 and have become widely implemented in modern browsers.

Let’s start with a simple example of a function called doSomething that accepts a parameter param1:

1
2
3
const doSomething = (param1) => {

}

To add a default value for param1 in case the function is invoked without specifying a parameter, you can modify the function like this:

1
2
3
const doSomething = (param1 = 'test') => {

}

The same concept can be applied to multiple parameters:

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

}

What if you have a unique object with parameter values in it? Previously, you would have to add additional code inside the function to handle the defaults if the options object was not defined:

1
2
3
4
5
6
7
8
const colorize = (options) => {
if (!options) {
options = {}
}

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

However, with destructuring, you can provide default values directly, simplifying the code:

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

Similarly, if you want to assign an empty object as the default value when no object is passed to the colorize function, you can do it like this:

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

With these techniques, you can easily set default parameter values in your JavaScript functions, making them more robust and user-friendly.

tags: [“default parameter values”, “JavaScript functions”, “ES6”, “destructuring”]