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
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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)