Is there a way to pass anonymous function as a custom callback function in Javascript? I have this code:
function notifyme(msg){
console.log(msg)
}
notifyme("msg", function(){
//do some custom redirect logic
});
I am trying the above code and it's executing notifyme function, but not going further with redirect code. I know I can pass a function name as a callback, but I don't have a specific function that I can pass. This is why they invented the anonymous function I guess.
It'd be really nice if there was a way to do that.
In JavaScript, callbacks and anonymous functions can be used interchangeably.
As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout() method.
Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
Your code pattern should be like
function notifyme(msg,callback){
console.log(msg);
// Do your stuff here
if(callback){
callback();
}
}
notifyme("msg", function(){
//do some custom redirect logic
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With