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 | 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 | const doSomething = (param1 = 'test') => { |
The same concept can be applied to multiple parameters:
1 | 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 | const colorize = (options) => { |
However, with destructuring, you can provide default values directly, simplifying the code:
1 | 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 | 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”]