Passing functions around

INPUT · Slides

Remembering that a function is a value

01 / 03

Whether or not you put ( ) on

The star of this chapter is treating a function as a value. Let us bring that back first.

  • hello … the function itself. You can carry it about
  • hello() … the result of running the function

Hand it to console.log without the () and it shows function. That means "this is a function".

const hello = () => {  console.log("hi");};console.log(hello);hello();

Result

function
hi

02 / 03

You were already handing functions over

Think back to what you wrote for forEach and map last chapter. What you handed over was the function itself, with no () on it.

Which is to say, you have already been "handing a function over as an argument" with your own hands.

const nums = [1, 2, 3];const twice = (n) => {  return n * 2;};console.log(nums.map(twice));

Result

[2, 4, 6]

03 / 03

What this chapter does

Last chapter you handed functions to things already provided, forEach and map. When the handed function got called was hidden inside the method, out of sight.

This chapter swaps the positions. You write the side that catches the function.

  • how to catch a function as an argument and call it
  • the flow of when the handed function runs
  • the machinery for handing values over as you call

First, a refresher. Here are problems you can solve with the tools you already have.