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
:
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:
const doSomething = (param1 = 'test') => {
}
The same concept can be applied to multiple parameters:
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:
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:
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:
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.