Callbacks and Tea

Callbacks and Tea
0

#1

I took a small break from FCC and I am now back on it. I am currently on the functional programming section and early on we are introduced to callback functions. It is somthing i have struggled with for a few month now. I was wondering if someone could help me wrap my head around the below problem, and just to give me another resource to read about callbacks. I understand the idea behind them, i think i am just struggling with the execution portion.

const prepareGreenTea = () => 'greenTea';


const prepareBlackTea = () => 'blackTea';

const getTea = (prepareTea, numOfCups) => {
  const teaCups = [];

  for(let cups = 1; cups <= numOfCups; cups += 1) {
    const teaCup = prepareTea();
    teaCups.push(teaCup);
  }

  return teaCups;
};

const tea4GreenTeamFCC = getTea('green Tea', 27) // :(
const tea4BlackTeamFCC = null; // :(

console.log(
  tea4GreenTeamFCC,
  tea4BlackTeamFCC
);

#2

can you attach the link to the challenge?

callback functions are just functions. If you can write a function, you can write a callback function.


#3

You want to pass the prepareGreenTea function as the first argument, because inside the getTea function, prepareTea will reference the prepareGreenTea function and then the following line will assign ‘greenTea’ to teaCup which will get pushed into the teaCups array which gets returned.

const teaCup = prepareTea();

The thing to understand here is that you can pass functions as arguments just like you can pass the number 27 as the second argument to getTea. Another way you could pass the same function as prepareGreenTea would be to pass it like:

const tea4GreenTeamFCC = getTea(() => 'greenTea',  27);

OR

const tea4GreenTeamFCC = getTea(function() { return 'green Tea'}, 27)

The above two ways are less readable, which is why the original code just declared the function, so all we have to do is pass the function name and the prepareTea variable inside the function references the same function of the same name passed in.