higher-order functions in JavaScript.

Vasant VyasVasant Vyas
2 min read

In JavaScript, higher-order functions (HOFs) are functions that can take other functions as parameters or return other functions. They are a fundamental concept in functional programming.

Benefits of HOFs

  • Reusable code: HOFs can be reused to write clean, expressive code.

  • Easy to debug: HOFs make it easier to debug code.

  • Abstraction: HOFs can abstract actions in a program.

  • Simplicity: HOFs make code simpler and easier to understand.

Examples of HOFs

  • Array.prototype.map(): Applies a function to every element in an array and returns a new array with the results

  • Array.prototype.reduce(): Iterates through an array and returns a single value

  • Array.prototype.forEach(): Executes a callback function on each element in an array in order

  • Array.prototype.filter(): Filters an array by returning a new array with only the elements that pass a test condition

Example of HOF :-

//  here are Cal is the function which takes the parameter as function and pass then to another function which is received as parameter.

let cal = function(opertion,a,b){
    return opertion(a,b)
}

let add = function(a,b){
    return a+b
}

let sub = function(a,b){        
    return a-b
}

let divide = function(a,b){
    return a/b
}

let multiply = function(a,b){   
    return a*b
}

console.log(cal(add,2,5))
console.log(cal(sub,2,5))
console.log(cal(divide,2,5))
console.log(cal(multiply,2,5))

// Find below result which is auto populated by Quokka JS.
cal(add, 2, 5): 7
cal(sub, 2, 5): -3
cal(divide, 2, 5): 0.4
cal(multiply, 2, 5): 10

"I think you'll find this blog post interesting!"…………………………………………..

0
Subscribe to my newsletter

Read articles from Vasant Vyas directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vasant Vyas
Vasant Vyas