Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 28, 2021 02:39 pm GMT

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.

Elqouent Javascript Chapter 5

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()

MDN article on .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

  1. Elqouent Javascript Chapter 5
  2. Code Wars Higher Order Function Questions
  3. FreeCodeCamp Article
  4. Great youtube vid

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To