DEV Community

Amirul Abu
Amirul Abu

Posted on

2 1

JavaScript Higher Order Example

This is an excerpt from Learning React


var createScream = function(logger) {
    return function(message) {
        logger(message.toUpperCase() + "!!!")
    }
}
const scream = createScream(message => console.log(message))

scream('functions can be returned from other functions')
scream('createScream returns a function')
scream('scream invokes that returned function')

It is a daunting task to really understand what is happening here. One of the immediate question is, how does the string in scream() can be passed all the way to logger then toUpperCase() then console.log()?

It is much clearer to understand using ES6 fat arrows


const createScream = (logger) => (message) => {logger(message.toUpperCase() + "!!!")}
const scream = createScream(message => console.log(message))
scream('functions can be returned from other functions')
scream('createScream returns a function')
scream('scream invokes that returned function')

If you don't understand it by now, don't worry. I will to break it down for you.

Here's another way of writing the code above, but skipping the higher order function, instead we hard-code the console.log() functionality.


const scream2 = (message) => {console.log(message.toUpperCase() + "!!!")}

scream2('the string is passed to message')

The string 'the string is passed to message' will go the scream2() parameter, then changed to uppercase and concatenated with exclaimation marks. This will happen first since they are in a bracket. Then the answer is console.log() out.

Another way of looking at it is by separating the functions.


function scream3(message) {
  return message.toUpperCase() + "!!!"
}

function logger(message){
    return console.log(message)
}

logger(scream3("this is another test"))

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay