Javascript Higher Order Functions and Callback functions

Javascript Higher Order Functions and Callback functions

In this article, I will explain what callback functions are and what higher-order functions are.

. Higher Order Functions

Higher Order functions are functions that take other functions as parameters. So basically, higher-order functions have other functions inside them. So they either accept the functions as an argument or return the functions. A simple example of a higher-order function is

function getStandard(standard) { // Invoke the passed function standard();
}
getStandard(function(){ console.log(‘elements’); Here, the getStandard function is the higher order function while the standard function is the parameter and this is called the callback function. Another example can be:

_function makeHigh(highLevel, fn) {

return fn(highLevel); } makeHigh(“Welcome to greatness”, console.log);//Welcome to greatness_

Here, the result is “Welcome to greatness” in your console.

One of the advantages of higher order function is that the code can be reused You do not have to write numerous functions that can be added as one function

function mimic1(mimic){ return console.log(mimi); } function mimic2(mimic){ return alert(mimic); } function mimic3(mimic){ return prompt(mimic); } function mimic4(mimic){ return confirm(mimic); } function mimic5(mimic){ return console.log(mimi + " from a callback function!");}

Instead of writing all these functions, we can write just one and pass another function to it. A function that is passed as an argument into another function is called a callback function.

. Callback Functions

Any function that is passed into another function as an argument is called a callback function. This is then invoked inside the outer function. Callback functions execute code in response to an event. Events could be events triggered by the user like the mouse hover, mouse click etc. This code might be executed at particular times and under certain circumstances based on the instruction you give to your code.

. Why do we need Callback Function

Callback functions are needed because javaScript actions are asynchronous hence, they do not stop the code from running until it is executed.

The major reason we have callbacks is to execute codes based on an event. An example of a callback:

_function magnet(color) { alert('Hello ' + color); }

function magnetDevice(callback) { var name = prompt('Please enter your name.'); callback(name); } magnet Device(magnet);_

setInterval, setTimeout are all examples of callback functions

My Twitter Handle: https://twitter.com/mchelleOkonicha

My LinkedIn Handle: https://www.linkedin.com/in/buchi-michelle-okonicha-0a3b2b194/