Passing functions around

INPUT · Slides

Catching a function as an argument

01 / 05

How is the calling side written?

Hand a function to forEach and it got called once per item. So how is the side doing the calling written?

In fact it does nothing special. It only puts () on the function it caught as an argument and calls it. You can write the same thing yourself.

02 / 05

Catch it and put ( ) on

Arguments have caught numbers and strings so far. A function is a value too, so it is caught in exactly the same way.

Put () on the argument you caught and its contents run. A function handed over as an argument like this is called a callback function.

const doTask = (task) => {  console.log("here we go");  task();};const clean = () => {  console.log("tidied up");};doTask(clean);

Result

here we go
tidied up

03 / 05

Handing it over does not run it

The clean in doTask(clean) has no () on it. So it was only handed over; nothing runs on this line.

It runs the moment the catching side writes task(). When to call is the catching side's decision. Follow the order in the example below.

const later = (fn) => {  console.log("not calling yet");  fn();  console.log("after calling");};const hello = () => {  console.log("hi");};later(hello);

Result

not calling yet
hi
after calling

04 / 05

Swap the function you hand over

Hand the same catching side a different function and the surroundings stay put while only the middle changes.

That is the joy of a callback function. You can write "the fixed work before and after" separately from "the work that changes each time".

const doTask = (task) => {  console.log("--- start ---");  task();};const wash = () => {  console.log("washed");};const cook = () => {  console.log("boiled");};doTask(wash);doTask(cook);

Result

--- start ---
washed
--- start ---
boiled

05 / 05

How many times is up to you as well

The function you caught need not be called only once. It runs as many times as you wrote the ().

Put it inside an if and you get "sometimes do not call it at all". How many times and when are both the catching side's freedom.

Right — let us write a function that catches a function.

const twice = (fn) => {  fn();  fn();};const beep = () => {  console.log("beep");};twice(beep);

Result

beep
beep