DEV Community

Cover image for ES6 Default Parameters
Tushar Kashyap
Tushar Kashyap

Posted on • Edited on

ES6 Default Parameters

Brief Introduction

Default parameters were released in ES2015 and are used to give default values to function parameters.

When the function is invoked without passing arguments, the default values are used instead.

function multiply(a, b = 3) {
  return a * b;
}

console.log(multiply(5));   // console logs 15
console.log(multiply(3, 2));   // console logs 6
Enter fullscreen mode Exit fullscreen mode

1. Use default parameters at the end.

Using default parameters at the start will require you to pass undefined as an argument (to use the default value) and then the other arguments. An example will make it more clear.

function multiply(a = 5, b) {
  return a * b;
}

console.log(multiply(undefined, 3));   // console logs 15
Enter fullscreen mode Exit fullscreen mode

whereas you could've done

function multiply(a, b = 5) {
  return a * b;
}

console.log(multiply(3));   // console logs 15
Enter fullscreen mode Exit fullscreen mode

2. Default parameters will also override an explicit undefined argument

With default parameters you cannot pass an undefined argument explicitly as seen in the above example. This is not a bummer as undefined is rarely passed as an argument.

function multiply(a, b = 5) {
  return a * b;
}

console.log(multiply(3, undefined));   // console logs 15
Enter fullscreen mode Exit fullscreen mode

3. Use parameters in subsequent default parameters.

What I mean by this is you can set the value of default parameters using the parameters to its left. For example -

function square(a, b = a) {
  return a * b;
}

console.log(square(3));   // console logs 9
Enter fullscreen mode Exit fullscreen mode

4. Call functions as default parameters

Functions invocations can also be used as default parameters. This will be clear with an example.

function square(x) {
  return x * x;
}

function addWithItsOwnSquare(a, b = square(a)) {
  return a + b;
}

console.log(addWithItsOwnSquare(3));   // console logs 12
Enter fullscreen mode Exit fullscreen mode

Please read the code slowly and you will understand what is happening here. This above example demonstrates both the points 3 and 4.

5. Define functions as default parameters

Functions can even be defined instead of being called in default parameters. This can be useful if you don't need this function elsewhere in your code.

function addWithTwenty(a, b = () => 20) {
  return a + b();   //   invoking the function here
}

console.log(addWithTwenty(10))   // console logs 30
Enter fullscreen mode Exit fullscreen mode

Note - These examples are only for demonstration and I don't write square and addWIthItsOwnSquare functions this way and you shouldn't too but it's always good to know the things you can do.

Top comments (0)