Back to Basics: What are Callbacks in JavaScript?

When learning JavaScript, it doesn’t take long until you encounter callbacks. These might seem strange and mysterious to beginners, yet it is very important to understand how they work in order to harness the power of the language. In this article I will teach you the basics of callbacks using easy-to-understand examples.

Callbacks — image via unsplash
What Is a Callback?
Simply put: A callback is a function that is to be executed after another function (normally asynchronous) has finished executing — hence the name ‘call back’.
More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument and subsequently called by the function that receives it, is called a callback function.
That’s a lot of words. Lets look at some examples to break this down a little more.

This article was first published on codeburst.io and is republished here with the author’s permission. If you enjoy reading, why not head over there and check out some of Brandon’s other articles? If you’d like to sharpen your JavaScript skills in general, why not head over to SitePoint Premium and sign up for our Introduction to JavaScript course.

Why Do We Need Callbacks?
For one very important reason — JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events. Lets look at a basic example:
function first(){
console.log(1);
}

function second(){
console.log(2);
}

first();
second();

As you would expect, the function first is executed first, and the function second is executed second — logging the following to the console:
// 1
// 2

All good so far.
But what if function first contains some sort of code that can’t be executed immediately? For example, an API request where we have to send the request then wait for a response? To simulate this action, were going to use setTimeout which is a native JavaScript method that calls a function after a specified delay. We’ll delay our function for 500 milliseconds to simulate an API request. Our new code will look like this:
Continue reading %Back to Basics: What are Callbacks in JavaScript?%

Link: https://www.sitepoint.com/callbacks-javascript/