In this tutorial, we will learn about Higher order functions in Javascript:
Higher Order Functions:
- Higher-order function is a function that takes one or more functions as arguments and/or returns a function
- Higher order functions allow for writing more abstract and reusable code
- Higher-order functions are widely used in functional programming and can be used to perform common operations such as filtering, mapping, and reducing arrays.
- They also allow for a more flexible and composable codebase.
Higher Order Function Example :
function display(func) {
func();
func();
}
function logToConsole() {
console.log("Hello!");
}
callTwice(logToConsole);
- In this example, the
display
function is a higher-order function that takes afunc
argument, which is a function - The
display
function calls thefunc
argument twice. - The
logToConsole
function is defined and passed as an argument todisplay
, so it is executed twice whendisplay
is called.
Higher Order Function Real time Examples:
In this example, it takes an array and a callback function as arguments and returns the first element in the array that satisfies the condition specified by the callback:
function findElement(array, callback) {
for (let i = 0; i < array.length; i++) {
if (callback(array[i])) {
return array[i];
}
}
return undefined;
}
const numbers = [1, 2, 3, 4, 5];
const firstEvenNumber = findElement(numbers, function(number) {
return number % 2 === 0;
});
console.log(firstEvenNumber); // 2
In this example, the findElement
function takes an array
and a callback
function as arguments. The findElement
function loops over the elements in the array
and calls the callback
function with each element. If the callback
function returns true
, the element is returned. If the loop finishes and no elements satisfy the condition, undefined
is returned.
The firstEvenNumber
constant is defined by calling findElement
with the numbers
array and a callback function that checks if the number is even. The result is logged to the console, which is 2
.
Thanks for Reading..