How to Use Callback Function in JavaScript



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

Sample Code

Below is sample code using a callback function.


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


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

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

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