Tutorial Playlist

JavaScript Tutorial: Learn JavaScript from Scratch

Overview

An Introduction to JavaScript: Here Is All You Need to Know

Lesson - 1

JavaScript Hello World: Here's What You Need To Know

Lesson - 2

All You Need to Know About JavaScript Arrays

Lesson - 3

Using Array Filter In JavaScript to Filter Array Elements

Lesson - 4

Everything You Need to Know About Array Reduce JavaScript

Lesson - 5

Introduction To JavaScript Loops: Do-While, For, For-In Loops

Lesson - 6

All You Need to Learn About Javascript Functions

Lesson - 7

The Best Guide on How to Implement JavaScript Closures

Lesson - 8

JavaScript “This” Keyword and How to Implement It

Lesson - 9

How to Implement JavaScript Form Validation

Lesson - 10

An Introduction Guide To JavaScript RegEx

Lesson - 11

How to Validate an Email Address in JavaScript?

Lesson - 12

All You Need to Know About JavaScript Promises

Lesson - 13

How to Implement JavaScript Async/Await

Lesson - 14

JavaScript DOM Tutorial: 2020 Edition

Lesson - 15

JavaScript Objects: Properties, Methods, and Accessors

Lesson - 16

An Introduction to Javascript Games: The Best Guide

Lesson - 17

An Easy Guide To Build A Calculator App In JavaScript

Lesson - 18

Javascript Projects: The Best Guide

Lesson - 19

What is OOP in JavaScript? How is it Implemented?

Lesson - 20

The Best Guide to Understanding JavaScript Learning Path

Lesson - 21

Java Vs .NET: Which Is the Best Technology to Choose?

Lesson - 22

Top 40 JavaScript Interview Questions You Should Know

Lesson - 23

Typeof in JavaScript: Checking Data Types Using the Typeof Operator

Lesson - 24

Tips and Tricks That You Should Know Before Going to a Coding Interview

Lesson - 25

Callback Functions in JavaScript

Lesson - 26
Callback Functions in JavaScript

A JavaScript callback is a function which is to be executed after another function has finished execution.

A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

Need of Callback Functions

We need callback functions because many JavaScript actions are asynchronous, which means they don't really stop the program (or a function) from running until they're completed, as you're probably used to. Instead, it will execute in the background while the rest of the code runs.

Let us look at a real world example to understand it (synchronous callback function) better.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard."

const button = document.getElementById('button');
function callback(){
console.log("Hello world");
}

button.addEventListener('click',callback);

In the above code, we add addEventListener as a function and we are passing another function callback as an argument. And when a click event is triggered the addEventListener registers the callback function.

Callback_functions_in_JavaScript_1

One More Example! (Asynchronous Callback Function)

If you wanted to download data from a server (which may take long durations of time), it would be wasteful for your program or function to just freeze while you waited for the data to be fetched. Instead, it's common practice to execute the fetching operation in the background.

This implies that if you have two functions in a row, one of which is asynchronous, function B will be performed while the other is still running. If function B is dependent on the data that function A is retrieving, you will run into issues.

async function fetchUsers() {
  const resp = await fetch('<https://jsonplaceholder.typicode.com/users>');
  const users = await resp.json();
  const names = users.map(({ login }) => login);
  console.log(names);
}

An async keyword is placed as a prefix to the function to make a function asynchronous.

The above function fetches fake user data of 10 users. We are then converting it to a json object to extract the user data.

The asynchronous functions return a promise, when the asynchronous function encounters the term await <promise> (notice that fetch() delivers a promise), it stops its execution until the promise is resolved. To read more about promises click here.

An asynchronous callback function differs from an asynchronous function. The higher-order function executes the asynchronous callback function in a non-blocking way. However, while waiting for promises (await promise>) to resolve, the asynchronous function stops its execution.

We can make this an asynchronous callback by adding it to an event, like a button click.

const button = document.getElementById('fetchusers');

button.addEventListeners('click', fetchUsers);

Callback_functions_in_JavaScript_2.

Free Course: JavaScript for Beginners

Learn the Basics of JavaScriptEnroll Now
Free Course: JavaScript for Beginners

Nesting Callbacks and Callback Hell

There are many ways to handle nested callbacks, using async await as discussed above, or using the old school way of promises (read about promises) or splitting the code into different functions.

Using Promises

We must generate a new promise for each callback in order to convert them to promises. When the callback is successful, we may resolve the promise. If the callback fails, we can reject the promise.

function getUserPromise {
  const newUser = getUserFromApi(user)

  return new Promise((resolve, reject) => {
    if (user) {
      resolve(user)
    } else {
      reject(new Error('No more new users!'))
    }
  })
}

Now you can create one more function and call the above function as a callback.

Using async-await

We have already seen how to create an asynchronous callback in the above section.

We can write asynchronous functions as if they are synchronous (executed sequentially) with the use of await as it stops the execution until the promise is resolved (function execution is successful).

const userProfile = async () => {
  const user = await fetchUsers(1) // argument indicated number of users to fetch
  const updatedAddress = await updateAddress(user)
  const pincode = await getPincode()
  const updateUser = await updateUser(user, updatedAdress, pincode)
  return user
}

// fetch and update user profile
userProfile()

You can nest these functions in promises as well.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

We have looked at the what and why's of callback functions in JavaScript, along with examples using synchronous and asynchronous functions to understand callbacks.

In the end we also covered what is nested callbacks and how to tackle them using promises and async-await.

To learn more about JavaScript and its amazing features which powers the websites, take the Full-Stack Web Development  course.

You can also sign up on our SkillUp platform to improve your software development knowledge. It is a Simplilearn initiative that offers free online courses to help you hone your skills in multiple programming languages, including JavaScript. 

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.