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 โญ๐