Callback in JavaScript

What are Callback Functions?

A callback function is a function that is passed as an argument to another function and is executed after (or during) the execution of that function. Think of it as "Hey, when you're done with your task, call me back and run this code."

Why Use Callbacks?

  1. Asynchronous Programming: Handle operations that take time (like API calls, file reading)
  2. Event Handling: Respond to user interactions (clicks, keypresses)
  3. Reusability: Write flexible functions that can perform different actions
  4. Control Flow: Decide what happens after a function completes

Simple Examples

1. Basic Callback Example


    function processUser(name, callback) {
        console.log('Processing ' + name);
        // After processing, call the callback
        callback(name);
    }

    function welcomeUser(name) {
        console.log('Welcome, ' + name + '!');
    }

    function notifyAdmin(name) {
        console.log('Admin: New user ' + name + ' joined');
    }

    // Using different callbacks
    processUser('John', welcomeUser);    // Processing John, Welcome John!
    processUser('Sarah', notifyAdmin);   // Processing Sarah, Admin: New user Sarah joined

2. Callbacks with Array Methods


    // map - transforms each element
    const numbers = [1, 2, 3, 4, 5];
    const doubled = numbers.map(function (num) {
        return num * 2;
    });
    console.log(doubled); // [2, 4, 6, 8, 10]

    // filter - keeps elements that pass a test
    const adults = [15, 20, 25, 17, 30].filter(function (age) {
        return age >= 18;
    });
    console.log(adults); // [20, 25, 30]

    // forEach - executes function for each element
    ['apple', 'banana', 'orange'].forEach(function (fruit, index) {
        console.log(index + ': ' + fruit);
    });
    // 0: apple
    // 1: banana
    // 2: orange

3. Event Listeners (Most Common Use)


    // Button click callback
    button.addEventListener('click', function () {
        console.log('Button was clicked!');
    });

    // Input change callback
    input.addEventListener('input', function (event) {
        console.log('You typed: ' + event.target.value);
    });

    // Multiple events, same callback
    function handleInteraction() {
        console.log('User interacted with element');
    }

    element.addEventListener('click', handleInteraction);
    element.addEventListener('focus', handleInteraction);

4. setTimeout and setInterval


    // Execute after delay
    setTimeout(function () {
        console.log('This runs after 2 seconds');
    }, 2000);

    // Execute repeatedly
    let counter = 0;
    const intervalId = setInterval(function () {
        counter++;
        console.log('Count: ' + counter);
        if (counter === 5) {
            clearInterval(intervalId); // Stop after 5
        }
    }, 1000);

5. Custom Functions with Callbacks


    // Success and error callbacks
    function fetchData(onSuccess, onError) {
        const randomSuccess = Math.random() > 0.5;

        setTimeout(() => {
            if (randomSuccess) {
                onSuccess('Data loaded successfully');
            } else {
                onError('Failed to load data');
            }
        }, 1000);
    }

    fetchData(
        function (data) { console.log('Success: ' + data); },
        function (error) { console.log('Error: ' + error); }
    );

6. Practical Example - Form Validation


    function validateForm(formData, onValid, onInvalid) {
        const errors = [];

        if (!formData.email.includes('@')) {
            errors.push('Invalid email');
        }
        if (formData.password.length < 6) {
            errors.push('Password too short');
        }

        if (errors.length === 0) {
            onValid(formData);
        } else {
            onInvalid(errors);
        }
    }

    // Usage
    const formData = { email: 'test@email.com', password: '12345' };

    validateForm(
        formData,
        function (data) {
            console.log('Form is valid, submitting...');
        },
        function (errors) {
            console.log('Validation errors:', errors);
        }
    );

Key Points to Remember

  1. Callbacks are just functions passed to other functions
  2. They don't execute immediately - they run when called
  3. Very common in JavaScript - especially for async operations
  4. Can be anonymous or named functions
  5. Enable flexible, reusable code

Where Callbacks are Used

  • DOM Events: clicks, keyboard input, mouse movements
  • Timers: setTimeout, setInterval
  • Array Methods: map, filter, reduce, forEach
  • AJAX/HTTP Requests: handling server responses
  • Node.js: file operations, database queries
  • Animations: requestAnimationFrame
  • Promise handlers: then, catch, finally

No comments:

Post a Comment

Debouncing and Throttling in JavaScript

Debouncing and Throttling - Made Simple! Think of these as traffic controllers for your functions: Debouncing = Wait until user stops, ...