JavaScript Interview Cheat-sheet

JavaScript Interview Cheat-sheet

In-depth Understanding of Callback() in simple way!

Table of contents

Call back

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action.

Let's Understand by Example

  var company = [ineuon,lco]

function addCompany (name)
 {
        setTimeout(function(){

        company. Push(name);

         },200);

 }

function getCompany()
{

setTimeout(function(){

console.log(company);

},100);

}

calling the function for output

addCompany('pensil');

getCompany();

you will get clear insight after the output!

Guees the Output?

Guys here what happen is we called the both of the function addComapny() and getCompany() but, because of setTimeout we get the output only of getComapny() function i.e [ineuon,lco].

[ineuon,lco]

Guys! we get the result vice-versa by changing the value of time we will get the output of less time of function.

For resolving this issue there is concept of Callback comes under the picture.

so let's see how i am using the concept of Callback()

  var company = [ineuon,lco]

function addCompany (name, callback)   
 {
        setTimeout(function(){

        company. Push(name);
        callback()                                    

         },200);

 }

function getCompany()
{

setTimeout(function(){

console.log(company);

},100);

}

addCompany('pensil',getComapny)

[ineuon,lco,pensil]

Guys! Here what happen is i passed the function through function .

Conclusion- Thanks for reading Guys! i Hope by reading this article you will surely master the concept of callback().