How to Pass JavaScript Function as Parameter

Anika Tabassum Era Feb 02, 2024
  1. Pass a General JavaScript Function as a Parameter
  2. Pass Both Function and Value to a JavaScript Function
How to Pass JavaScript Function as Parameter

In JavaScript, passing a function as a parameter to another function is similar to passing values. The way to pass a function is to remove the parenthesis () of the function when you assign it as a parameter.

In the following sections, a function pass is demonstrated as a parameter.

Pass a General JavaScript Function as a Parameter

For this drive, we will initiate a function func2 with a code body and directly pass it to the function func1. Later, after assigning func2 to func1, we will call the func2 aka function_parameter.

function func1(function_parameter) {
  function_parameter();
}

function func2() {
  console.log('okay!');
}

func1(func2);

Output:

passing javascript function as parameter_1

The example depicts that func2 is passed to func1. And when func1 is called, it checks its argument (func2) and previews the code fenced by func2.

Pass Both Function and Value to a JavaScript Function

JavaScript allows the passing of function and value together in another function, making functions more dynamic. This declaration will require an input of integer, bool, string, or maybe even a function, and the other parameter is the function parameter.

We will see two examples of this category.

Function and value as function parameters:

function pass(value) {
  return ('Hello ' + value);
}

function receive_pass(x, func) {
  console.log(func(x));
}

receive_pass('David', pass);

Output:

function_and_value_pass

Two functions as function parameters:

function pass1(value) {
  return ('Hello ' + value);
}

function pass2() {
  return (' Howdy!');
}

function receive_pass(func1, func2) {
  console.log(func1('world!') + func2());
}

receive_pass(pass1, pass2);

Output:

two javascript functions as parameter

As per the code instances, JavaScript takes functions as a parameter like any other regular data type. The core difference is when a function is called in the parenthesis of the argument, functions should be removed; otherwise, this can cause an error while running.

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Function

Related Article - JavaScript Parameter