Signup/Sign In
PUBLISHED ON: FEBRUARY 21, 2023

JavaScript Program to Pass a Function as Parameter

This guide will show you how to use JavaScript to pass a function as a parameter in your own code. A solid grounding in JavaScript Functions and Function Expressions is required for comprehension of this article. It's a simple task that can be completed with minimal programming. You can also get certified after completing our interactive JavaScript course, which covers everything from the fundamentals to advanced topics in the language. You can get more information about the course here.

How to Use Function as Parameter

In the above program, there are two functions named as : name() and greetings().

  • The name() function takes two parameters, basically the user and the message.
  • The greetings() function is passed as an argument inside the name() function.

Program to Pass a Function as Parameter

// JavaScript Program to pass a function as a parameter

function greetings() {
    return 'Hello';
}

// passing function greet() as a parameter
function name(user, func){

    // accessing the passed function
    const message = func();

    console.log(`${message} ${user}`);
}

name('Apple', greetings);
name('Ball', greetings);
name('Cat', greetings);


Hello Apple
Hello Ball
Hello Cat

Conclusion

SO in this article, we saw how to pass a function as a parameter in JavaScript. Function arguments are passed to the function in the same way that variable arguments are passed to the function. for the purpose of returning parameters from a function.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.