DEV Community

Cover image for Callback Function in JS
Kesavarthini
Kesavarthini

Posted on

Callback Function in JS

What is a Callback Function?

A callback function is a function that is passed as an argument to another function and is executed later.

Simple Definition
“A function inside another function”

Callback Function – Real-Life Examples
1. Washing Clothes

function washClothes(callback) {
    console.log("Clothes are washed");
    callback();
}

function dryClothes() {
    console.log("Clothes are drying");
}

washClothes(dryClothes);
Enter fullscreen mode Exit fullscreen mode

Explanation:
First → clothes are washed
Then → drying happens

Output:

Clothes are washed
Clothes are drying
Enter fullscreen mode Exit fullscreen mode

2. Cooking Food

function cookFood(callback) {
    console.log("Cooking food...");
    callback();
}

function serveFood() {
    console.log("Food is served");
}

cookFood(serveFood);
Enter fullscreen mode Exit fullscreen mode

First cooking → then serving

3. Mobile Charging

function chargePhone(callback) {
    console.log("Phone is charging...");
    callback();
}

function usePhone() {
    console.log("Now you can use the phone");
}

chargePhone(usePhone);
Enter fullscreen mode Exit fullscreen mode

First charge → then use

4. Studying

function study(callback) {
    console.log("Studying...");
    callback();
}

function takeTest() {
    console.log("Taking test");
}

study(takeTest);
Enter fullscreen mode Exit fullscreen mode

First study → then test

5. Login System

function login(callback) {
    console.log("User logged in");
    callback();
}

function showDashboard() {
    console.log("Welcome to dashboard");
}

login(showDashboard);
Enter fullscreen mode Exit fullscreen mode

First login → then dashboard

Top comments (0)