Telerik blogs
JavaScriptT2 Dark_1200x303

In today’s post, we will be looking into callback functions in JavaScript and how they can be used in our workflows.

What Are Callback Functions?

All JavaScript functions are objects. Some of them have parameters and some of them do not. A callback function is the type of JavaScript function that has another function passed in as an argument to be executed at a later time.

You probably already use callback functions in your workflow without even knowing it. Consider this line:

button.addEventListener(‘click’, toggleFunction)

If you have worked with buttons, you might have come across something similar to the line above. The addEventListener is already a function, and the toggle function is another function passed into it as an argument.

Why Are Callbacks Important?

So the very nature of JavaScript is that code is executed line by line from left to right. Think of a series of simple functions in JavaScript like this:

function firstOne(){
    console.log('This is the first function created')
}
function secondOne(){
    console.log('This is the Second function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
firstOne()
secondOne()
thirdOne()

Now if you run this code, you’ll see that it returns this in your console:

This is the first function created
This is the Second function created
This is the Third function created

That is how JavaScript works, line by line from left to right. Now what if the second function had to fetch data from an external database or was delayed for any other reason? The other commands should keep executing while the second one fetches the data and then executes. This is what callback functions are for—making sure that functions do not run before tasks are successfully done so that those tasks which would not execute immediately can be taken care of without breaking the application or stopping other processes.

These are elements of asynchronous operations in JavaScript, which keep your codebase more efficient and less error-prone. Let us see how it works with a setTimeOut method.

function firstOne(){
    console.log('This is the first function created')
}
function secondOne(){
    console.log('This is the Second function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
firstOne()
setTimeout(secondOne, 2000)
thirdOne()

Here we added the setTimeOut method to the mix and passed secondOne as an argument. This method only executes right after the specified milliseconds—in our case 2000, which is 2 seconds. This is the output:

This is the first function created
This is the Third function created
This is the Second function created

How Callbacks Are Used

There are about three ways you can use callback functions. The first way is what we have seen already. Let us optimize it even further:

function firstOne(){
    console.log('This is the first function created')
}
function secondOne(){
    console.log('This is the Second function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
firstOne()
setTimeout(secondOne, 2000)
thirdOne()

The second way is using an anonymous function, which looks like this:

function firstOne(){
    console.log('This is the first function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
setTimeout(function(){
    console.log('This is the Second function created')
}, 2000)
firstOne()
thirdOne()

Here you see all of it is defined directly inside of the setTimeOut function instead of a named function that is called later. This is even a cleaner approach.

The other option is using the ES6 arrow function. It is very similar to the anonymous function.

function firstOne(){
    console.log('This is the first function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
setTimeout(() =>{
    console.log('This is the Second function created')
}, 2000)
firstOne()
thirdOne()

Nesting Callback Functions

The great thing about callback functions is that you can nest other callback functions inside them. This means that a callback function can contain another callback function. So let’s see one in action with our current example.

function firstOne(){
    console.log('This is the first function created')
}
function thirdOne(){
    console.log('This is the Third function created')
}
setTimeout(() =>{
    console.log('This is the Second function created')
    setTimeout(thirdOne, 3000)
}, 2000)
firstOne()

Here we put the thirdOne in a setTimeOut function and then inside a callback function. If you run the code, you will notice that it runs first, second, third because of the timers set.

Wrapping Up

Callback functions are a great way to stretch the power of functions in JavaScript and use async operations with ease. They provide developers with great flexibility options and ways to manage outcomes. Nesting callbacks can be a great thing, but you have to be careful as you can get into a callback hell, where you might nest a lot of functions and find it hard to trace the origins. Happy hacking!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.