🥨Passing Functions

In JavaScript, you can pass a function as an argument to another function. This is called "passing a function as a parameter".

For example, consider the following code:

const greet = (name) => {
  console.log(`Hello, ${name}!`);
};

const sayHello = (callback) => {
  callback('John');
};

sayHello(greet);  // "Hello, John!"

sayHello((name) => {
  console.log(`Hi, ${name}!`);
});  // "Hi, John!"

In this example, we have a function called greet that takes a single argument (name) and logs a greeting to the console. We also have a function called sayHello that takes a single argument (callback).

When we call the sayHello function and pass the greet function as an argument, the sayHello function calls the greet function and passes it the string 'John' as an argument. This causes the greet function to log the string "Hello, John!" to the console.

You can also pass anonymous functions (functions without a name) as arguments. For example:

sayHello((name) => {
  console.log(`Hi, ${name}!`);
});  // "Hi, John!"

In this case, we are passing an anonymous function that logs a different greeting to the console as an argument to the sayHello function.

Passing functions as arguments can be useful when you want to write code that is flexible and can be customized by the caller. For example, you might write a utility function that can perform some operation on an array of data, and allow the caller to specify the operation to be performed by passing a function as an argument.

Last updated