JavaScript Fundamentals: Callbacks

What is a callback? How do you write callbacks? What are some examples of callbacks?

JavaScript Fundamentals: Callbacks
JavaScript Fundamentals: Callbacks

JavaScript callback functions are a great way to add functionality to your web page without having to write a lot of code. They are easy to use and can be used to add features such as animations, forms, and even interactive games.

JavaScript callbacks are functions that are passed as arguments to other functions.

When the other function is executed, it calls the callback function.

Callbacks help to make code cleaner by breaking it up into smaller pieces that can be executed independently. Clean code matters in JavaScript because it can make code more readable and maintainable. It can also make code more error-prone and difficult to debug.

How to write a callback function in JavaScript

Callbacks are often used with event handlers. When an event occurs, the event handler calls the callback function.

Here is an example of a callback function:

function sayHello(name) {
  console.log('Hello, ' + name + '!');
}

function greeting(callback, name) {
  callback(name);
}

greeting(sayHello, 'Squirrel');

In the above example, the greeting function accepts a callback function and a name as arguments. The greeting function then calls the callback function, passing the name as an argument.

The callback function then prints a greeting to the console.

When to use callback functions in JavaScript

There are many use cases for callbacks. One common use is to delay the execution of a function until an asynchronous operation has completed. For example, you might want to wait until an image has finished loading before displaying it.

Here is a list of potential scenarios where callback functions are used in JavaScript:

  • When you need to execute a function after another function has finished running
  • When you need to execute a function repeatedly, such as in a loop
  • When you need to execute a function based on certain conditions being met
  • When you need to execute a function asynchronously

Another common use is to create a reusable function that can be used in different contexts. For example, you might want to create a function that formats a date in a specific way. This function could be passed to different components that need to display dates.

More examples of callbacks in action

Here is an example of formatting a date string where an anonymous function is passed in as the callback:

function formatDate(date, callback) {
  var result = callback(date);
  return result;
}

var date = new Date();

formatDate(date, function(date) {
  return date.toLocaleDateString();
});

Additional examples of callbacks in JavaScript include:

  • A function passed as an argument to the Array.prototype.forEach() method
[1,2,3].forEach(function(element, index, array) {
  console.log("I'm at index " + index + " of " + array);
});
  • A function passed as an argument to the jQuery $.ajax() method

$.ajax({
  url: "test.html",
  success: function(result){
    $("#div1").html(result);
  }
});
  • A function passed as an argument to the setTimeout() method
setTimeout(function() {
  console.log('I am a callback!')
}, 1000)
💡
Want to check out my other stuff? See my link wall at Zipply.io.