Understanding use of closure in callback in javascript

21 views Asked by At

I am trying to understand how closure is used in callback function in javascript.Can anybody explain me in detail ?

 function fetchData(url, callback) {
  fetch(url)
    .then((response) => response.json())
    .then((data) => callback(data))
    .catch((error) => console.error(error));
 }
  
 //callback
 function processData(data) {
   console.log(data);
 }
  
 fetchData("https://jsonplaceholder.typicode.com/todos/1", processData);

The callback function 'processData()' in fetchData function has access to the data variable in its outer scope,which is the result of the fetchData function.

As callbacks behave as if they are actually placed inside that function, they are in practice closures: they can access the containing function’s variables and parameters, and even the variables from the global scope. `

I tried reading articles regarding same online yet I am not able to convince myself.

0

There are 0 answers