Tiago Ruivo
Tiago Ruivo

Reputation: 183

If a function is executed inside another function, would it immediatly qualify as a callback func?

I been reading some definitions about callbacks, and on FCC, it states that:

"Callbacks are the functions that are slipped or passed into another function to decide the invocation of that function."

Now, this created some confusion because on the following prepareTea() would qualify as a callback:

const prepareTea = () => 'greenTea';

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

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

  return teaCups;
};

But as far as I read, to be a callback, it needs to be passed in as arg.

Could you clarify?

Thank you

Upvotes: 0

Views: 80

Answers (2)

user5536315
user5536315

Reputation:

The term callback is a bit blurry. Let's look at two related terms with more precise semantics:

Higher Order Function

A HOF takes at least one function argument. In Javascript the term is also used for functions that return another function, but this is uncommon.

Continuation

A continuation in a language without continuations on a language level is always encoded by continuation passing style. A CPS function takes a continuation k as its last argument and calls k with its result value, i.e. a CPS function doesn't return a result but passes it to its continuation.

Conclusion

A callback function is clearly an higher order function. It is also a CPS function but without the constraint that it has to take the continuation as its last argument.

Upvotes: 1

Ahmet Can G&#252;ven
Ahmet Can G&#252;ven

Reputation: 5462

A callback is a function that is passed into another function as an argument to be executed later.

When you take a look at the ECMAScript specification, you will see that parameter names are callbackFn which expecting a function as an argument.

Your code is not using any callback functions but we can convert it together to make it use.

const prepareTea = () => 'greenTea';

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

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

  console.log('Created cups');
  callbackFn(teaCups);
};

const callbackFunction = cups => {
  console.log('Number of cups', cups.length);
}

getTea(4, callbackFunction); // Pass callbackFunction as an argument to getTea

We have used callbackFunction as a callback. We defined it as a regular function but used it as a callback. So this means we can use any function as a callback.


Why prepareTea is not used as a callback?

Because you used its return value directly. If your prepareTea function is defined like below:

const prepareTea = cb => cb('greenTea');

And you use this function as:

prepareTea(tea => teaCups.push(tea));

Then you can say that you used the prepareTea function as a callback.

Upvotes: 3

Related Questions