JavaScript Program to Pass a Function as Parameter

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example: Function as Parameter

// program to pass a function as a parameter

function greet() {
    return 'Hello';
}

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

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

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

name('John', greet);
name('Jack', greet);
name('Sara', greet);

Output

Hello John
Hello Jack
Hello Sara

In the above program, there are two functions: name() and greet().

  • The name() function takes two parameters.
  • The greet() function is passed as an argument to the name() function.

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community