DEV Community

Cover image for Dummy Proof: Callback Functions
jennman
jennman

Posted on

Dummy Proof: Callback Functions

What is a callback function?

  • A function passed as an argument inside of a function that will be executed later

When to use a callback ?

  • You can use callbacks in asynchronous functions, where one function has to wait for another function to invoke.

Regular Function :

function name(argument){
   //do something 
}
Enter fullscreen mode Exit fullscreen mode

Callback Function :

//Defining functions
function prepare(ingredients, callback) {
       console.log("Preparing " + ingredients);
       callback();
}

//callback function
function chop(){
       console.log("Chopping");
}

//Calling the function
prepare("onions and garlic", chop);
Enter fullscreen mode Exit fullscreen mode
function createQuote(quote, callback){ 
  var myQuote = "Like I always say, " + quote;
  callback(myQuote); // 2
}

function logQuote(quote){
  console.log(quote);
}

createQuote("eat your vegetables!", logQuote); // 1

// Result in console: 
// Like I always say, eat your vegetables!
Enter fullscreen mode Exit fullscreen mode

Things to know about callback functions :

  • It's a function that is passed as an argument to another function
  • Does not have to be named 'callback' in the argument
  • This function is called a higher-order function which contains the logic for when the callback function gets executed
  • JavaScript has anonymous functions which lets you declare and execute functions without naming them.
  • Callback functions can be anonymous functions

Resources:

Top comments (0)