An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
December 28, 2021 02:39 pm GMT
Original Link: https://dev.to/zachinjapan/higher-order-functions-4h7e
Higher Order Functions
I was recently confused by this simple question.
/*Declare a function 'add'.'add' takes one number input: 'x'.'add' returns a function that takes one number input 'y'.This returned function returns the sum of 'x' and 'y' when run.*/
Did you try to solve it? Here is one possible answer
function add(x) { return function innerFunction(y) { return x + y }}//exampleconst addTwo = add(2) //stores the inner function with x inheritedconst sum = addTwo(3) // inputs y as 3//sum = 5
That my friend, is a higher order function.
Functions that operate on other functions,either by taking them as arguments orby returning them, are called higher-order functions.
The code above is an example of returning a function that inherits the outer scope's function's variable
Here is an example of using a function as an input
const add = (num1, num2) => { return num1 + num2}const multiply = (num, multiplier) => { return num * multiplier}// exampleconsole.log(multiply(add(3, 7), 10)) // 100
Not too scary after all.
You might have noticed that there are a few Array Methods that take functions as inputs.... well....
that.....
makes them HIGHER ORDER FUNCTIONS!!
My favorite array method
Array.prototype.map()
const array1 = [1, 4, 9, 16]// pass a function to mapconst map1 = array1.map(x => x * 2)console.log(map1)// expected output: Array [2, 8, 18, 32]
Cool right?
Here are some free resources
Did you enjoy this article? Or did I get something wrong?
Feel free to contact me using my website
Have a fantastic day!
Original Link: https://dev.to/zachinjapan/higher-order-functions-4h7e
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To