Last active
June 23, 2017 05:57
-
-
Save chriswrightdesign/76e3c7a0766718ef224f784480808112 to your computer and use it in GitHub Desktop.
Closure and higher-order function example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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