DEV Community

Discussion on: Functional programming basics part 2: Higher order function

Collapse
 
alvarocaceresmu profile image
Álvaro Cáceres Muñoz

Excellent article! By the way, I did not catch why is it useful to return a function as an output... could anybody please give me a practical example? Thanks.

Collapse
 
stevetwitte profile image
Stephen Taylor Witte

If your code had to call a function depending on some other logic, you could return the function to call from the function that decides. Make sense?

Collapse
 
alvarocaceresmu profile image
Álvaro Cáceres Muñoz

You mean something like returning different functions in a switch statement, for example?

Thread Thread
 
stevetwitte profile image
Stephen Taylor Witte

Right

Thread Thread
 
alvarocaceresmu profile image
Álvaro Cáceres Muñoz

Now I get it, thanks!

Collapse
 
ysael profile image
ysael pepin • Edited

Hi Alvaro,

thanks :)

let's say we want to create a greeter function that will take a greeting copy but we know that this copy will change depending on the context.

we can do:


const greeter = copy  => {
    return name => `${name} ${copy}`
}

const politeGreeter = greeter('you are very welcome here')
const weirdGreeter = greeter('you look weird today!')

console.log(politeGreeter('Ysael')) // Ysael you are very welcome here
console.log(weirdGreeter('Ysael')) // Ysael you look weird today!

witch will allow us to make different greeter functions.

Hope that helps :)