Higher order functions and closures example in Javascript

First with โ€œnormalโ€ functions:

//closures and higher order function
function salute(salutation) {
  return function(firstName) {
    return function(lastName) {
      console.log(`hi ${salutation} ${firstName} ${lastName}`)
    }
  }
}

salute('Mr.')('John')('Wick')

//output
hi Mr. John Wick

The shorter variant with arrow functions:

const saluteArrowFunction = (salutation) => (firstName) => (lastName) => console.log(`hi ${salutation} ${firstName} ${lastName}`);

saluteArrowFunction ('Mr.')('Johnny')('Cage')

//output
hi Mr. Johnny Cage

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions


Shared with from Codever. ๐Ÿ‘‰ Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github โญ๐Ÿ™

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

Use test.each in jest to avoid repetitive tests

This blog post makes a case for using jest test.each wherever possible, by refactoring an existing test, thus making the code more concise and maintainable and reduce code duplication Continue reading