11.3. Passing Functions as Arguments

Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action. This turns out to be extremely useful.

Examples best illustrate this technique, so let's look at a couple now.

11.3.1. Example: setTimeout

The built-in function setTimeout allows a programmer to pass a function, specifying that it should be called at a later point in time. Its basic syntax is:

setTimeout(func, delayInMilliseconds);

Example

Suppose we want to log a message with a 5 second delay. Since five seconds is 5000 milliseconds (1 second = 1000 milliseconds), we can do so like this:

1function printMessage() {
2   console.log("The future is now!");
3}
4
5setTimeout(printMessage, 5000);

Console Output

"The future is now!"

Try It!

Is the call to printMessage actually delayed? Don't just take our word for it, try this yourself. Play with our example to change the delay.

The function printMessage is passed to setTimeout the same as any other argument.

A common twist often used by JavaScript programmers is to use an anonymous function as an argument.

Example

This program has the same behavior as the one above. Instead of creating a named function and passing it to setTimeout, it creates an anonymous function within setTimeout's argument list.

1setTimeout(function () {
2   console.log("The future is now!");
3}, 5000);

Examples like this look odd at first. However, they become easier to read over time. Additionally, code that passes anonymous functions is ubiquitous in JavaScript.

11.3.2. Example: The Array Method map

The array method map allows for every element in an array to be mapped or translated, using a given function. Here's how to use it:

let mappedArray = someArray.map(functionName);

When the map method executes, the following actions occur:

  1. The first element in someArray is passed into functionName as an argument.
  2. functionName executes and returns a new value.
  3. The return value is added to mappedArray.
  4. Steps 1 - 3 repeat for each element in someArray.

When complete, mappedArray, contains each of the individual return values from the mapping function, functionName.

Example

 1let nums = [3.14, 42, 4811];
 2
 3let timesTwo = function (n) {
 4   return n*2;
 5};
 6
 7let doubled = nums.map(timesTwo);
 8
 9console.log(nums);
10console.log(doubled);

Console Output

[3.14, 42, 4811]
[ 6.28, 84, 9622 ]

Notice that map does not alter the original array.

When using map, many programmers will define the mapping function anonymously in the same statement as the method call map.

Example

This program has the same output as the one immediately above. The mapping function is defined anonymously within the call to map.

1let nums = [3.14, 42, 4811];
2
3let doubled = nums.map(function (n) {
4   return n*2;
5});
6
7console.log(doubled);

Console Output

[ 6.28, 84, 9622 ]

11.3.3. Check Your Understanding

Question

Similar to the map example above, finish the program below to halve each number in an array.

1let nums = [3.14, 42, 4811];
2
3// TODO: Write a mapping function
4// and pass it to .map()
5let halved = nums.map();
6
7console.log(halved);

Question

Use the map method to map an array of strings. For each name in the array, map it to the first initial.

1let names = ["Chris", "Jim", "Sally", "Blake", "Paul"];
2
3// TODO: Write a mapping function
4// and pass it to .map()
5let firstInitials = names.map();
6
7console.log(firstInitials);