Callback function with parameters JavaScript | Example code

You can pass some parameter to a function used as callback in JavaScript.

These two options would look like this:

function firstfunction(callback) {
    // code here
    callback(arg1, arg2);
}

firstfunction(callbackfunction);

Or

function firstfunction(callback) {
    // code here
    callback();
}

firstfunction(function() {
    callbackfunction(arug1, arug2);
});

Callback function with parameters in JavaScript Example

HTML example code:- Using the arguments variable like so:

<html>
<body>

	<script>
		function tryMe (param1, param2) {
			alert(param1 + " and " + param2);
		}

		function callbackTester (callback) {
			callback (arguments[1], arguments[2]);
		}

		callbackTester (tryMe, "Hello", "callback");
	</script>
</body>
</html>

Output:

Callback function with parameters JavaScript

Read more: JavaScript callback function

Do comment on this topic if you have any doubts and suggestions.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.