JavaScript Higher Order Example

amirulabu

Amirul Abu

Posted on February 23, 2019

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

💖 💪 🙅 🚩
amirulabu
Amirul Abu

Posted on February 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Higher Order Example
javascript JavaScript Higher Order Example

February 23, 2019