...

/

Multiple Default Parameters

Multiple Default Parameters

Learn the rules to pass multiple default parameters in different situations.

Playing with default and regular parameters

A function can have any number of default parameters. For example, let’s define a function with one regular parameter and two default parameters.

Press + to interact
'use strict';
//START:CODE
const fetchData = function(
id,
location = { host: 'localhost', port: 443 },
uri = 'employees') {
console.log('Fetch data from https://' +
location.host + ':' + location.port + '/' + uri);
};
//END:CODE
//START:CALL1
fetchData(1, { host: 'agiledeveloper', port: 404 }, 'books');
fetchData(1, { host: 'agiledeveloper', port: 404 });
fetchData(2);
//END:CALL1

Explanation

This function’s caller can pass three arguments, pass two arguments and leave out the value of the last parameter, or pass one argument and leave out both of the default parameters.

  • In the first call, in line 14, the given values are used for all three parameters, as we can see in the output.
  • In the second call, in line 15, the default value is used for the uri parameter.
  • In the
...
Access this course and 1400+ top-rated courses and projects.