Passing functions around

INPUT · Slides

Writing the function on the spot

01 / 04

Does something used once need a name?

So far you have written it in two steps: make a function into a variable, then hand that variable over.

But naming a function you hand over only once is a bit of a waste. Thinking of the name is work, and reading it means going back and forth between the lines.

In fact you can write the function straight where the argument goes.

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

Result

tidied up

02 / 04

How to rewrite it

What it does is the same as before. Only two steps.

  • delete the const name =
  • put the remaining () => { ... } where the argument goes

The unfamiliar bit is the }); at the end, two closers in a row. But read them apart — } ends the function, ) ends the call — and you will not get lost.

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

Result

beep
beep

03 / 04

Array methods take this shape too

The function you hand forEach or map can be written on the spot as well. In real code this is the shape you see most.

Since it goes without a name, it is also clear at a glance that it is work for this spot only.

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

Result

10
20
30

04 / 04

Which should you write?

The answer is "whichever reads better". Roughly this is the guide.

  • write it on the spot … it finishes in a few lines, used once
  • give it a name … handed over many times, long inside, or the name explains the meaning

Either works, so when in doubt give it a name. Shortening it later is easy.

Right — let us practise writing them on the spot.