Functions as Parameters

Functions are called “first-class citizens” in JavaScript because they can be stored in variables or passed into functions,not less than any other datatype.

Passing one function into another allows you to have more control over when and how a function gets executed.

Passing a function

function say(something) {
  console.log(something);
}

function exec(func, art) {
  func(arg);
}

exec(say, 'Hi, there');

Passing an anonymous function

function exec(func, art) {
  func(arg);
}

exec((something) => {
  console.log(something);
}, 'Hi, there');
Usage of setTimeout()

Using function-passing, this is how you would set up the function add to run after 5 seconds, and this is how would you pass its arguments 2 and 2 when it runs.

function add(num1, num2) {
  console.log(num1 + num2);
}

window.setTimeout(add, 5000, 2, 2);

Another Example

window.setTimeout((something) => {
  console.log(something);
}, 3000, 'Hi, there');