How to Pass Function as Parameter in JavaScript

avatar
Published: Jan 14, 2021 - Updated: Mar 16, 2022

Hi devs, in this article, I’m going to show how to pass function as parameter in JavaScript. Let’s have a look at some examples:

Table of Contents

  1. Example 1
  2. Example 2

Example 1

Have a look at an example:

function add(a, b) {
  return a+b;
}

function subtract(a, b) {
  return a-b;
}

function calculation(pass_function) {
  var x = 10;
  var y = 5;

  return pass_function(x, y);
}

console.log(calculation(add));       // 15
console.log(calculation(subtract));  // 10

Example 2

Take a look at another example:

function addBook(id, refreshCallback) {
  refreshCallback();
}

function refreshBookList() {
  console.log('Load all books');
}

addBook(1, refreshBookList); // Load all books

We can also pass argumets if we needed:

function addBook(id, refreshCallback) {
  refreshCallback(id);
}

function refreshBookList(id) {
  console.log('New book id: ' + id);
}

addBook(1, refreshBookList); // New book id: 1
That’s all, artisans. Thanks for reading. ?

Comments

No comments yet…