1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
5

JavaScript Callbacks

Updated on 05/08/2024334 Views

The callback function in JavaScript is an essential part of web development. I firmly believe that this is especially true if we are using JS-based tech stacks such as MEAN or MERN.

As a JS developer, learning about the callback function early on can save you a lot of trouble and time. More than anything, callbacks allow us to write more modular code. We can pass different callback functions to the same core function depending on what we want to do with the result.

Also, I think it is important to note that JavaScript heavily relies on events (clicks, data loading, etc.). The callback function in JavaScript defines what happens in response to those events.

Let us learn about this function in detail and we will also explore some JS callback example programs.

What is the Callback Function in JavaScript?

A callback function is a function that is passed as an argument to another function. The outer function can then execute the callback function at a specific point in its own operation. 

JavaScript is asynchronous, meaning it doesn't wait for one task to completely finish before starting another. Callbacks are essential to manage the results of operations that take time (e.g., network requests, timers, user interactions).

Here are the key benefits of callback JavaScript:

  • Non-blocking execution: Your main JavaScript code doesn't freeze while waiting for long operations. Your website or application remains responsive.
  • Better user experience: Users don't have to stare at a frozen screen waiting; they can keep interacting with other elements.
  • Efficient resource management: JavaScript can handle multiple tasks concurrently, making optimal use of its time.

Synchronous vs. Asynchronous Execution

When it comes to synchronous execution, code is executed line by line in the order it's written. Each operation must finish before the next begins in this method. We will learn about both the executions with a synchronous execution example and callback function javascript example.

Example:

function taskA() { console.log("Task A done"); }

function taskB() { console.log("Task B done"); }

taskA(); 

taskB(); 

// Output: Task A done -> Task B done 

Meanwhile in asynchronous executive, some operations can start but might take time to finish. JavaScript doesn't wait, it moves on to other tasks while the longer operation is running in the background. Call back in JavaScript is used to signal when an asynchronous task is done.

Example:

Code:

function longTask(callback) {

    console.log("Long task started");

    setTimeout(function() { 

        console.log("Long task finished");

        callback(); 

    }, 3000); // Simulate a 3-second delay

}

longTask(function() {

    console.log("Callback executed");

});

UNderstanding How the Callback Function in JavaScript Works

I think that the structure of a callback function itself is straightforward, but I feel that understanding its usage in context is key.

Here is an example:

function greet(name, callback) {

    console.log('Hello, ' + name + '!');

    callback(); 

}

In the above code, greet is the main function. It takes two parameters:

  • name: A string.
  • callback: A reference to the function that will be called later.

Callback functions can take their own parameters. This lets the main function pass data to them.

Code snippet:

function processData(data, callback) {

     // Do something with the 'data'

     let result = data * 2; 

     callback(result);

}

We pass a callback by giving its name (without the parentheses) as an argument to the main function.

Example:

function myCallback(result) {

    console.log("The result is:", result);

}

processData(5, myCallback); // Pass 'myCallback' as the callback

Callbacks often need to handle both success and failure.

Here is an example:

function doSomething(data, callback) {

    // Attempt something that might fail

    if (success) {

        callback(null, resultData); // First param is error (null if none)

    } else {

        callback(errorObject, null);  

    }

}

Closures play a significant role with callbacks. When a callback is defined inside another function, it captures the variables from its surrounding scope. This allows it to access data even after the outer function has finished executing. When it comes to fetching data from an API, synchronous execution is not the ideal choice and we should always go for asynchronous execution.

Incorrect way (synchronous execution):

function fetchDataSync() {

     let result = // ... 

     return result;

}

Correct way (asynchronous execution):

function fetchDataAsync(callback) {

    // Code to make API request

    callback(dataFromAPI); 

}

Building a Simple Image Loader With Callback Function in JavaScript

index.html code:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Image Loader</title>

  <link rel="stylesheet" href="styles.css"> 

</head>

<body>

  <script src="script.js"></script> 

</body>

</html>

styles.css code:

/* Very basic styling to center an image */

body {

    display: flex;

    justify-content: center;

    align-items: center;

    min-height: 100vh; 

    margin: 0;

}

script.js code:

function loadImage(imageUrl, callback) {

  const image = new Image(); 

  image.onload = function() {

    callback(null, image); // Success!

  };

  image.onerror = function() {

    callback(new Error('Could not load image')); 

  };

  image.src = imageUrl;

}

// Usage:

loadImage('https://www.upgrad.com/_ww3-next/_next/static/media/upGrad-logo.6366986e.svg', function(error, image) {

  if (error) {

    console.error(error);

  } else {

    document.body.appendChild(image);

  }

});

In this above example, loadImage takes an image URL and a callback function. It creates an image element and sets event listeners for both success (onload) and failure (onerror). The callback is executed when either event happens, providing an error (if any) and the image object.

If you wish to master JS and become a full stack developer, you can check out upGrad’s full stack development courses.

Creating a Dynamic Form With Callback Function in JavaScript

index.html code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dynamic Form</title>

    <link rel="stylesheet" href="styles.css">

</head>

<body>

    <div class="form-container">

        <label for="countrySelect">Choose a Country:</label>

        <select id="countrySelect">

            <option value="">--Select--</option>

            <option value="USA">USA</option>

            <option value="Canada">Canada</option>

            <option value="UK">UK</option>

        </select>

        <label for="cityInput">Choose a City:</label>

        <input type="text" id="cityInput" disabled> 

    </div>

    <script src="script.js"></script>

</body>

</html>

styles.css code:

.form-container {

    width: 400px;

    margin: 20px auto;

    padding: 20px;

    border: 1px solid #ddd;

}

label {

    display: block;

    margin-bottom: 5px;

}

select, input[type="text"] {

    width: 100%;

    padding: 8px;

    margin-bottom: 15px;

    border: 1px solid #ccc;

    border-radius: 4px; 

}

script.js code:

const selectBox = document.getElementById('countrySelect');

const cityInput = document.getElementById('cityInput');

selectBox.addEventListener('change', function() {

  const selectedCountry = selectBox.value;

  loadCitiesForCountry(selectedCountry, function(error, cities) {

    if (error) {

      console.error(error);

    } else {

      cityInput.disabled = false; // Enable the city input

      // Update the city input with available options 

    }

  });

});

// Simulate loading cities based on country

function loadCitiesForCountry(country, callback) {

  // ... Implementation to fetch cities

In this example, a change event on the country dropdown triggers the callback. Inside the callback, we fetch relevant cities (simulated by loadCitiesForCountry). If successful, the city input is enabled and populated.

In the index.html file, we use div to hold the form elements neatly and <select> dropdown with options for countries. We also have a <text> input which is initially disabled.

Practical Applications With the Callback Function in JavaScript

We have already gone through a lot of function callback javascript examples in the above sections, let us learn about some other applications of callback js with other methods.

Event Listeners

The addEventListener method attaches a callback function to the button's 'click' event. When the button is clicked, the callback is executed.

Example snippet:

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

button.addEventListener('click', function() {

    console.log('Button was clicked!');

    // Do other things in response to the click

});

Timers

setTimeout and setInterval can control how callbacks execute code after specified delays.

Example snippet of setTimeout:

// Single execution after a delay

setTimeout(function() {

    console.log("This message appears after 2 seconds");

}, 2000); 

Example snippet of setInterval:

// Repeated execution at an interval

setInterval(function() {

    console.log("This message appears every second");

}, 1000);  

AJAX Requests

AJAX requests help us fetch data from a server and process it when ready.

Example snippet:

function makeRequest(url, callback) {

    const xhr = new XMLHttpRequest();

    xhr.open('GET', url);

    xhr.onload = function() {

        if (xhr.status === 200) {

            callback(null, xhr.responseText); 

        } else {

            callback(xhr.status, null);

        }

    };

    xhr.send();

}

RequestAnimationFrame

RequestAnimationFrame provides a smoother and more efficient way to create animations than setTimeout or setInterval.

Example snippet:

function animate() {

  // Update animation state 

  requestAnimationFrame(animate); // Callback creates a loop 

}

animate(); // Start the animation

Transitions

We use transitions to listen for the end of CSS transitions to execute further actions.

Example snippet:

const element = document.getElementById('myElement'); 

element.addEventListener('transitionend', function() {

    console.log("Transition complete!");

});

Web Workers

Offload heavy computations or long-running tasks to web workers to keep your main UI thread responsive. Communication with web workers is often done through callbacks.

Example snippet:

const worker = new Worker('computation-worker.js');

worker.onmessage = function(event) {

    const result = event.data;

    // Process the result from the worker 

};

worker.postMessage(data); // Send data to the worker 

Callback in Node js

Node.js heavily relies on asynchronous operations like reading files. Callbacks depend on how you handle the results in Node.js environments.

Here is a callback in node js example:

const fs = require('fs');

fs.readFile('data.txt', 'utf-8', function(err, data) {

    if (err) {

        console.error(err);

    } else {

        console.log(data);

    }

});

Modularization and Code Reusability

Functions like map, filter, and reduce in JavaScript arrays frequently use callbacks to define operations on each element.

Example snippet:

const numbers = [1, 2, 3, 4];

const doubledNumbers = numbers.map(function(number) {

    return number * 2;

}); 

console.log(doubledNumbers); // [2, 4, 6, 8]

Tips and Best Practices for Using the Callback Function in JavaScript

Now that I have callbacks JavaScript explained to you, I would like to share some tips and best practices for using them.

When it comes to error handling, I firmly believe that we should follow these protocols:

  • Always include a way to handle errors in your callbacks.
  • Use the first argument of the callback function (error) to signal errors.
  • Provide meaningful error messages.

And, when it comes to naming conventions, I recommend that you follow these:

  • Use verb phrases to describe the action the callback will take (e.g., handleImageLoad, processFormSubmission)
  • Consider prefixes like "on" for event-related callbacks (onClick, onSubmit)

Wrapping Up

Now that we have explored callback function JS, I would want to mention that promises provide a cleaner syntax compared to raw callbacks when dealing with chains of asynchronous actions. Promises are objects that represent the eventual success or failure of an asynchronous operation. 

Also, when you have multiple nested asynchronous operations that depend on each other, using raw callbacks can lead to deeply indented, hard-to-manage code. Promises (and async/await) help flatten this structure and improve readability. We will learn about all these in the later tutorials or you can join upGrad’s software development courses to start mastering tools such as JavaScript.

Frequently Asked Questions

What is callback function in JavaScript?

A callback function is a function passed as an argument to another function, which is then executed inside the outer function when a specific action or event occurs.

What is callback function in JavaScript interview questions?

Interviewers often ask about callbacks to assess your understanding of asynchronous programming, event handling, and code design patterns in JavaScript.

What is the use case of callback function?

Callbacks are used to manage the results of asynchronous operations (like network requests, timers, or user interactions) and continue execution in a non-blocking manner.

What is the difference between callback function and normal function in JavaScript?

Callback functions are designed to be executed at a later time (often after an asynchronous operation), while normal functions are executed immediately when called.

What type is a callback function?

Callback functions are simply 'function' type objects in JavaScript.

What is difference between function and callback function?

All callback functions are functions, but not all functions are callback functions. The distinction is in how they are used.

Why is it called a callback function?

It's called a "callback" because the outer function "calls you back" when a specific task is completed or an event happens.

What is standard callback function?

There's no strict "standard" form, but callbacks usually have the signature (error, data) => {} to handle potential errors and provide results.

What is callback function in structure?

Structurally, callbacks are just like any other function. The key difference lies in how and when they are executed.

image

mukesh

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...