Passing functions around

INPUT · Slides

Handing values to a callback

01 / 05

Who was putting the item in?

The function you handed forEach caught an argument, as in (item) => { ... }. Who was putting that item in?

The answer is forEach's side. When it called the function it caught, it wrote fn(item).

You just write the value inside the brackets as you call. The same as any function call.

02 / 05

Hand a value over as you call

Call the function you caught as fn(10) and 10 goes into the handed function's argument. The one dealing values out is the one calling.

The handing side just writes one argument, expecting "something will arrive".

const useValue = (fn) => {  fn(10);};useValue((n) => {  console.log(n * 3);});

Result

30

03 / 05

The catching side decides the name

What name the 10 in fn(10) is caught under is up to how the handed function is written. n or count, either works.

The only fixed thing is the order. The first value goes into the first argument. So you can hand two over.

const useTwo = (fn) => {  fn(4, 5);};useTwo((height, width) => {  console.log(height * width);});

Result

20

04 / 05

Dealing them out while looping

You should be able to picture the inside of forEach now. It is only going round the array, handing each item over and calling.

You can make the same thing yourself. The eachOf below traces how forEach is built.

const eachOf = (arr, fn) => {  for (let i = 0; i < arr.length; i++) {    fn(arr[i]);  }};eachOf(["red", "blue"], (c) => {  console.log(c);});

Result

red
blue

05 / 05

You can catch a return value too

What the handed function returns, the caller can catch. Just put it in a variable, as in const answer = fn(6);.

That find and filter wanted "a function that returns true", and map wanted "a function that returns the converted value", was because they were looking at this.

Right — let us write a callback that gets values dealt to it.

const useResult = (fn) => {  const answer = fn(6);  console.log(`the answer is ${answer}`);};useResult((n) => {  return n * n;});

Result

the answer is 36