Skip to content

Instantly share code, notes, and snippets.

@chriswrightdesign
Last active June 23, 2017 05:57
Show Gist options
  • Save chriswrightdesign/76e3c7a0766718ef224f784480808112 to your computer and use it in GitHub Desktop.
Save chriswrightdesign/76e3c7a0766718ef224f784480808112 to your computer and use it in GitHub Desktop.
Closure and higher-order function example
// example of a higher order function: .map() on arrays, map expects a function callback
[1,2,3].map(num => num + 1); // [2, 3, 4];
// closures in es5 syntax
function getValue(property) {
return function(obj) {
return obj && obj[property];
}
}
// closures in es6/2015 syntax
const getValue = property => obj => obj && obj[property];
// our example object
const userInfo = {
name: 'sarah',
id: '12345',
country: 'Australia',
};
// invocation of our closure
getValue('name')(userInfo); // Result: 'sarah'
// an example of our closure combined with a higher order function
const addMe = x => y => x + y;
[1, 2, 3].map(addMe(1)); // [2, 3, 4];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment