JavaScript Program to Pass a Function as Parameter

Updated on December 20, 2024
Pass a function as parameter header image

Introduction

JavaScript, as a highly flexible and dynamic scripting language, brings a lot of power through its first-class functions. This means in JavaScript, functions can be treated like any other variable; they can be assigned to variables, returned from other functions, and crucially, passed as parameters to other functions. Passing functions as parameters, often referred to as callback functions, allows for more modular, reusable, and flexible code structures that can handle complex asynchronous operations.

In this article, you will learn how to effectively pass functions as parameters in JavaScript through diverse examples. Discover how this approach can be utilized in various scenarios including event handling, asynchronous programming, and array manipulation.

Basics of Passing Functions as Parameters

Basic Example: A Function That Executes Another Function

  1. Define a function that accepts another function as a parameter.

  2. Inside this function, execute the passed function.

    javascript
    function greet(name) {
        return `Hello, ${name}!`;
    }
    
    function executeGreetFunction(fn, userName) {
        return fn(userName);
    }
    

    Here, executeGreetFunction accepts a function fn and a string userName as parameters. fn is then called with userName as its argument inside executeGreetFunction.

Calling the Function

  1. Call executeGreetFunction by passing the greet function and a name as arguments.

    javascript
    const message = executeGreetFunction(greet, 'Alice');
    console.log(message); // Outputs: Hello, Alice!
    

    This code shows how executeGreetFunction is utilized to call the greet function dynamically with the parameter 'Alice', demonstrating the flexibility of passing functions as arguments.

Advanced Usage in Asynchronous Programming

Handling Asynchronous Operations

  1. Define a function that performs an asynchronous operation using setTimeout.

  2. Pass a callback function to handle the event after a delay.

    javascript
    function delayedLog(message, callback) {
        setTimeout(() => {
            console.log(message);
            callback();
        }, 2000);
    }
    

    In this example, delayedLog takes a string and a callback function, then uses setTimeout to delay the console log action. The callback function is called after the log completes.

Executing the Asynchronous Function

  1. Create and pass a callback function to handle actions after the timeout.

    javascript
    delayedLog('This message displays after 2 seconds.', () => {
        console.log('Delay complete.');
    });
    

    This usage demonstrates an asynchronous operation where the callback function is executed once the preceding log is completed after a delay.

Utilizing Functions in Array Operations

Example: Array Manipulation with Function Parameters

  1. Apply a function to every element of an array using Array.map().

    javascript
    const numbers = [1, 2, 3, 4, 5];
    const squares = numbers.map(function(num) { return num * num; });
    console.log(squares); // Outputs: [1, 4, 9, 16, 25]
    

    This example takes an array of numbers and uses map() to create a new array squares, where each element is the square of the corresponding element in the original array. The function used to calculate the square is passed as a parameter to map().

Conclusion

Passing functions as parameters in JavaScript unlocks a range of possibilities for writing more concise, modular, and readable code. Whether it's handling asynchronous operations elegantly, dynamically invoking functions, or manipulating collections, the pattern of leveraging first-class functions is a powerful tool in any JavaScript developer's arsenal. Implement these strategies in your projects to enhance code quality and maintainability.