How to Pass Function as Parameter in JavaScript

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. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.