CuteMachine

JavaScript Function Parameter Defaults

Default parameters have been added in the ES6 version of the JavaScript standard.

Since then you can provide default values like so:

const name = (name = 'nobody') => name

name()    // 'nobody'
name('John')    // 'John'

JavaScript Parameter Expressions

You can set the default for a parameter using an expression. This expression is called a parameter expression.

const someValue = 21

const calcSomething = (n = someValue) => {
  return n * 2
}

calcSomething()     // 42

JavaScript default parameters work with arrow functions, as in the above example, but also with function declarations and function expressions.

It is essential to keep in mind that the function expression gets evaluated when it is called and not when it is declared.

function getZero() {
  return 0
}

const doubleIt = (n = getZero()) => {
  return n * 2
}

doubleIt()     // 0
doubleIt(2)    // 4

JavaScript Parameters Can Depend On Previous Parameters

You can set the default for a parameter using any parameter earlier in the same parameter list.

const rect = (width = 1, height = width) => {
  return { width, height }
}

rect()    // { width: 1, height: 1 }
rect(5)    // { width: 5, height: 5 }
rect(5, 20)    // { width: 5, height: 20 }

Be careful: If you try to set the default using a parameter that comes later in the parameter list, you will get a ReferenceError.

Destructuring With Default Parameters

When you use destructuring with parameters, you can also define defaults. There is no greeting provided in the highlighted line, but it will be set through the default when the greetPerson() function is called.

const greetPerson = ({ name, greeting = 'Hello' }) => {
  return `${greeting} ${name}`
}

greetPerson({ name: 'John'})    // 'Hello John'
greetPerson({ name: 'Bella', greeting: 'Ciao'})    // 'Ciao Bella'

Default Values For Rest Parameters

You cannot set a default for the rest parameter explicitly. JavaScript provides an empty array for the rest parameter when it is not set. Setting a default value ensures that the rest parameter is never undefined. You can read my tutorial on Rest Parameters In JavaScript for more information.

Conclusion

Defaults for function parameters are an excellent addition to the JavaScript language. It is an excellent way to ensure that your functions have sensible defaults.

Even though we can use expressions to initialize parameters, it is probably a better idea to use constant values, because the code will be much easier to understand.

I also refrain from using defaults that depend on a parameter earlier in the parameter list.

Posted on CuteMachine.

Jo's Profile ImageWritten by Jo who lives and works in Frankfurt building digital doodah. Stalk him on Twitter.

TOS • Privacy • Disclaimer