JavaScript …….. Callback

Keesha Hargrove
2 min readDec 3, 2021

What is a Callback?

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

With the help of a callback function, we can perform asynchronous things inside javascript. — — from https://anuradha.hashnode.dev/callback-functions-in-javascript?guid=none&deviceId=1e0313bf-20dc-478d-a0b4-d2edbcfed390

More complexly put: For JavaScript, functions are objects. . Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function. — http://www.topcoder.com/thrive/articles/callbacks-and-higher-order-functions-in-javascript

Let’s look at some examples….

Why do we need Callbacks?

It’s event driven in JavaScript. Therefore, JavaScript will continue to execute instead of waiting for a response before proceeding. Lets look at the example below:

function one(){
console.log(1);
}function two(){
console.log(2);
}one();
two();

To look at , the function one is executed first, and the function two is executed second —in the console it will look:

// 1
// 2

When a function one contains some sort of code that can’t be executed immediately? Like an API request where we have to send the request then wait for a response? To show the use of of setTimeout which is a JavaScript function that calls a function after a set amount of time. We’ll delay our function for 300 milliseconds to simulate an API request. This is how it would like:

function one(){
// Simulate a code delay
setTimeout( function(){
console.log(1);
}, 300 );
}function two(){
console.log(2);
}one();
two();

Inside of our 300 millisecond delay. This is what happen when invoke the functions?

one();
two();// 2
// 1

When logged out the result of the one() function after the two() function, even though the one()was invoked first.

JavaScript didn’t execute our functions in the order we wanted.

Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.

--

--