ES2015 Lesson 3 – Default Arguments


First we will examine ES5 hacks to provide default arguments. Then we will explore default arguments in ES6.

Hacks in ES5

In some cases, function arguments are optional. For instance, let’s check the following code:

Three arguments of addCalendarEntry are optional.

A popular shorthand for optional parameters in ES5 uses the || (logical or) operator. You can make use of the shortcuts of logical operations.

The value value || defaultValue is value, whenever value is truthy. If the first operand of an || expression is truthy, the second operand is not even evaluated. This phenomenon is called a logical shortcut.

When value is falsy, value || defaultValue becomes defaultValue.

While this approach looks nice on paper, shortcuts are sometimes not flexible enough. All falsy values are treated in the same way, including 0, '', false. Sometimes, we may want to treat a 0 differently than an undefined indicating the absence of a value.

The ES6 way

ES6 supports default values. Whenever an argument is not given, the default value is substituted. The syntax is quite compact:

Suppose function f is given with two arguments, a and b.

When a and b are not supplied, the above function is equivalent with

Default arguments can have arbitrary types and values.

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. However, a0 cannot be a function of b, as b is declared later.

Use default arguments at the end of the argument list as optional arguments. Document their default values.

The arguments array is not affected

In earlier versions of JavaScript, we often used the arguments array to handle variable number of arguments:

Bear in mind that the arguments array is not affected by the default parameter values in any way. See the third exercise for more details.

Exercises

As always, the link to the solutions is at the end of the 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.


Exercise 3 Determine the values written to the console.


Solutions