Default Arguments
First we will examine ES5 hacks to provide default arguments. Then we will explore the ES6 version. This is a short lesson, therefore, it is your chance to learn the most from the exercises.
Hacks in ES5
In some cases, function arguments are optional. For instance, let's check the following code:
function addCalendarEntry( event, date, length, timeout ) {
date = typeof date === 'undefined' ? new Date().getTime() : date;
length = typeof length === 'undefined' ? 60 : length;
timeout = typeof timeout === 'undefined' ? 1000 : timeout;
// ...
}
addCalendarEntry( 'meeting' );
In the above example, three arguments are optional. Most people use the ||
for default parameters.
function addCalendarEntry( event, date, length, timeout ) {
date = date || new Date().getTime();
length = length || 60;
timeout = timeout || 1000;
// ...
}
addCalendarEntry( 'meeting' );
The reason why this approach is wrong is that all falsy values are substituted with the defaults. This includes 0
, ''
, false
.
The ES6 way
ES6 supports default values. Whenever an argument is not given, the default value is substituted. The syntax is quite compact:
function addCalendarEntry( event, date = new Date().getTime(), length = 60, timeout = 1000 ) {
// ...
}
addCalendarEntry( 'meeting' );
Default argument values can be any values.
function f( a = a0, b = b0 ) { ... }
When a
and b
are not supplied, the above function is equivalent with
function f() {
let a = a0;
let b = b0;
...
}
All considerations for let declarations including the temporal dead zone holds. a0
and b0
can be any JavaScript expressions, in fact, b0
may even be a function of a
.
The arguments
array is not affected by the default parameter values in any way. See the third exercise for more details.
Use default arguments at the end of the argument list for optional arguments. Document their default values.
Exercises
Exercise 1. Write a function that executes a callback function after a given delay in milliseconds. The default value of delay is one second.
Exercise 2. Change the below code such that the second argument of printComment
has a default value that's initially 1
, and is incremented by 1
after each call.
function printComment( comment, line ) {
console.log( line, comment );
}
Exercise 3 Determine the values written to the console.
function argList( productName, price = 100 ) {
console.log( arguments.length );
console.log( productName === arguments[0] );
console.log( price === arguments[1] );
};
argList( 'Krill Oil Capsules' );