How to Use Callback Function in JavaScript

02/10/2022

Contents

In this article, you will learn how to use callback function in JavaScript.

What is a callback function?

A callback function is a function that is passed as an argument to another function.
Callback functions are often used as event handlers.
An event handler is a function that is executed when some event occurs, such as when a button is clicked or when communication is completed.

The usage of the callback function is as follows.
The callback function func1 is passed as an argument to func2.

let func1 = function() {
  // do something
}
func2(func1);

Sample Code

Below is sample code using a callback function.

HTML

// Click the button to call the callback function
<button onclick="func1()">Click</button>

JavaScript

// Callback Function
function cbFunc1(name) {
  console.log("Hello!", name);
}

// Function that calls a callback
function hello(name, callback) {
  callback(name);
}

// Function called when a button is pressed
function func1() {
  hello('foo', cbFunc1);
}