How to set default parameter values in JavaScript
By Flavio Copes
Learn how to set default parameter values in JavaScript functions, the ES6 way with param = value, and how to set defaults for destructured options objects.
To set a default parameter value in JavaScript, you assign it right in the function signature, with param = value. If the caller doesn’t pass that parameter, the default kicks in.
Default parameter values have been introduced in ES6 in 2015, and are widely implemented in modern browsers.
This is a greet function which accepts a name:
const greet = (name) => {
console.log(`Hello ${name}`)
}
We can add a default value for name, used when the function is invoked without a parameter:
const greet = (name = 'guest') => {
console.log(`Hello ${name}`)
}
greet('Flavio') //Hello Flavio
greet() //Hello guest
This works for more parameters as well, of course:
const greet = (name = 'guest', greeting = 'Hello') => {
console.log(`${greeting} ${name}`)
}
Defaults only apply to undefined
The default is used when the parameter is undefined. That includes passing undefined explicitly.
Be careful with null though. It’s a real value, so the default does not apply:
greet(undefined) //Hello guest
greet(null) //Hello null
This bites people when a value comes from somewhere else, like an API response, and happens to be null. If you want a fallback for null too, handle it inside the function.
Defaults can use earlier parameters
A default value can be an expression, and it can reference the parameters before it:
const addTax = (price, tax = price * 0.22) => {
return price + tax
}
addTax(100) //122
addTax(100, 10) //110
The default is evaluated at call time, every time it’s needed.
Defaults with an options object
What if you have a unique object with parameters values in it?
Once upon a time, if we had to pass an object of options to a function, to have default values of those options if one of them was not defined, you had to add a little bit of code inside the function:
const colorize = (options) => {
if (!options) {
options = {}
}
const color = ('color' in options) ? options.color : 'yellow'
//...
}
With destructuring you can provide default values, which simplifies the code a lot:
const colorize = ({ color = 'yellow' }) => {
//...
}
There’s a catch, though. Call colorize() with no arguments and it throws:
colorize()
//TypeError: Cannot read properties of undefined (reading 'color')
That’s because you can’t destructure undefined. The fix is to assign an empty object as the default for the whole parameter:
const spin = ({ color = 'yellow' } = {}) => {
//...
}
Now calling spin() works, and color gets its 'yellow' default. I always add the = {} when a function takes an options object. It makes every option truly optional, object included.
Related posts about js: