Pass a JavaScript function as parameter
In JavaScript, you can pass a function as an argument to another function as you would any variable. Here's a quick and simple example:
Here, the runCallback
function receives greet
as a callback (cb) and executes it using 'Alice'
as the name. Make no mistakes dear coder, this is no wizardry, it's modulo mercantile JavaScript!
Code-wise function handling
Passing by Reference, not by a Broomstick!
JavaScript allows passing a function by reference. It meanly heartlessly discards the magical parentheses. Why? So the function is not called right then and there! Here, have a look:
Check before you Wreck!
Invoking a non-existent function or a non-function (oops!) can cause a TypeError
. A safety check using typeof
can save the day!
Scope and Butter
Want to retain scope while passing callbacks with arguments? Use object binding methods like .bind()
. It's as smooth as butter.
Expert Function Hacks
Argumentative Callbacks
Need to call a callback with specific arguments? .apply()
or .call()
are your friends. They accept arguments aplenty!
Anonymous Shields
To protect the scope of arguments when a callback calls, use an anonymous function. It's the medieval shield you didn't know you needed.
Asynchronous Function-sharing
When dealing with asynchronous tasks such as server calls or event loops, function passing becomes a life-saver.
Pitfall Dodging
To dodge the null trap or an unwanted undefined, make sure to check if the function you're calling isn’t one of those. Or, make it default to a noop (no operation) function.
Was this article helpful?