ES2015 Lesson 3 – Default Arguments – Solutions


Exercise 1. Write a function that executes a callback function after a given delay in milliseconds. The default value of delay is one second.

Solution:

Exercise the code by running:

Your function prints 'done' in 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.

Solution:

Default values can be any JavaScript expressions, so the ++ post-increment is perfectly fine.

We want to avoid complicated expressions in the function signature for stylistic reasons, based on the principles of writing maintainable, easy to understand code. Therefore, consider moving more complex logic from default argument value expressions to separate functions:

This way, if the line numbering logic changes, you don’t have to edit hard to read default parameter expressions.

Notice that the code is side-effect free. This will be an important concept in React, Redux, and ImmutableJs. We generally want to avoid side-effects, this is why I suggest not using ++ and -- at all.


Exercise 3. Determine the values written to the console.

Solution:

The output value is:

To understand the role of arguments, let’s see the original function:

Let’s transform this function into its equivalent on condition that the second argument is not supplied:

From this form, it is easy to conclude that

  • arguments.length is 1,
  • arguments[1] is undefined, and is not equal to 100.