Callbacks in Javascript

Asked

Viewed 490 times

0

I’d like to understand something about callbacks! I know there are other topics on the subject, but mine is a simple question and is not clear to me yet.

For example, let’s assume I have this array:

['Banana', 'Maçã', 'Melancia']

To go through the same I will use the foreach with a function and I will display with console.log

const minhaArray = ['Banana', 'Maçã', 'Melancia'];

function impri(nome, indice){
  console.log(`${indice + 1}. ${nome}`);
}

minhaArray.forEach(impri);

The callback in the case, is only the function impri or callback is all together? The function impris together from the array and foreach?

2 answers

3


Callback or Callback Function is the function that is passed to another function, and that will be called later when needed.

Confirm the definition of Callback Function on MDN

So in your example, callback is the function impri, for it is she who is passed to forEach.

3

The concept of callback is more common in asynchronous cases. It is possible to say that impri is the callback, although the concept itself is most common in asynchronous processes, because it is the function that is passed as argument and will be called back.

In this case, to answer your question: impri is the callback, the function itself and not the set where it is used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.