
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Passing a function as a callback in JavaScript
Following is the code for passing a function as a callback in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Passing a function as a callback</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to pass the add2() function as callback to multiply9() function</h3> <script> let resEle = document.querySelector(".result"); function add2(a) { return a + 2; } function multiply9(fn, num) { return fn(num) * 9; } document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = "The number returned = " + multiply9(add2, 12); }); </script> </body> </html>
Output
On clicking the ‘CLICK HERE’ button −
- Related Articles
- Passing parameters to callback functions JavaScript
- Accumulating some value over using a callback function and initial value in JavaScript
- Callback function in C
- Passing unknown number of arguments to a function in Javascript
- How to invoke a JavaScript Function as a function?
- Passing a 2D array to a C++ function
- What are callback functions in JavaScript?
- Explain the callback Promise.finally in JavaScript
- Passing an array to a C++ function
- How to invoke a JavaScript Function as a method?
- Explain the role of callback function in AJAX
- How to access a function property as a method in JavaScript?
- Passing empty parameter to a method in JavaScript
- Passing two dimensional array to a C++ function
- JavaScript display the result of a function as HTML?

Advertisements