Home > Enterprise >  function that passes in a function as an argument and returns an anonymous function
function that passes in a function as an argument and returns an anonymous function

Time:01-29

What is this paradigm called in javascript ? After reading other paradigms it doesn't seem to fit into the following list:

  • HOC
  • Factory function
  • Currying

We have a function that passes in a function as an argument and returns an anonymous function

const getCode = () => {
    return 'ABCDE'
}

const myFunction = ( fnc ) => {
 const value = fnc()
 return (msg) => {
    console.log(`returned function with passed in message = ${msg}`)
    return value
 }
}

const parseMe = myFunction(getCode)
const value = parseMe('hi there') 

end value is 'ABCDS')

CodePudding user response:

It seems like what you're looking for is closures.
See : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

CodePudding user response:

It's no necessary a functional programming concept in itself. It's just the use of high-order function in which function is as a first citizen so can be pass as argument but also return and encompass a closure in it.

And with this we can obtain function composition thinking! Which is a core concept around functional programming.

If you are interessed with all the potential of such high order functions allow. You can progressivly tend into more advance functional programming concepts such as functor, monoid, applicative and monad. Eventually to have the whole sight withoutbeing afraid of math take a glance at Categroy Theory.

I wish you good continuation into the path of functional programming it can be quite abstract but it definitely worth it!

  • Related