DEV Community

Alaguselvan T
Alaguselvan T

Posted on

CALLBACK FUNCTION IN JS

DEFINITION:
A callback function is a function that is passed as an argument to another function and is executed after a specific task is completed.
or
A callback is a function that is called later by another function.

function greet(name, ak) {
    console.log("Hello " + name);
    ak();
}

function sayBye() {
    console.log("Goodbye!");
}

greet("Alagu", sayBye); 
Enter fullscreen mode Exit fullscreen mode

Explain About code:

  1. greet() is the main function.
  2. sayBye() is the callback function.
  3. After greeting, greet() calls callback().

SetTimeout:
SetTimeout() is a built-in JavaScript function that executes a function after a specified delay.
Basic:

console.log("Start");

setTimeout(function () {
    console.log("Hello, JavaScript!");
}, 2000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Explanation:
"Start" is printed.
setTimeout() starts a 2-second timer.
"End" is printed immediately.
After 2 seconds, the callback function runs and prints "Hello, JavaScript!".

Named Function:

function welcome() {
    console.log("Welcome to the Blog Platform!");
}

setTimeout(welcome, 3000);
Enter fullscreen mode Exit fullscreen mode

Advantages of Callback Functions
Makes code reusable.
Helps execute code after another task finishes.
Essential for asynchronous programming.
Used in events, timers, and API requests.
Improves code organization.

Disadvantages of Callback Functions
Nested callbacks can make code difficult to read.
Too many callbacks can lead to callback hell.
Debugging nested callbacks can be harder.

Top comments (0)