Last active
May 14, 2016 09:02
-
-
Save vjefri/8a38bcc5e8d3bed04743e7cc6ce4305e to your computer and use it in GitHub Desktop.
This file contains 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
/* ES6 the Lazy Way */ | |
var nums = [1, 2, 3, 4, 5, 6] | |
// You don't have to use braces when it is a simple expression | |
// No need to say return, it just knows | |
// The fat arrow is creating the function | |
// If we have one arg, no need to add parens | |
var odds = nums.map(v => v + 1); // [ 2, 3, 4, 5, 6, 7 ] | |
// Same things as above is the take away | |
// We have to use `()` if we have more than one arg | |
var all = nums.map((v, i) => v + i); // [ 1, 3, 5, 7, 9, 11 ] | |
// We return an array of objects without saying return explicitly | |
// If we include comma we have to add `()` to return | |
// In this case we have to wrap the object in `()`, same for arrays | |
var pairs = nums.map(v => ({even: v, odd: v + 1})); | |
/* | |
Output: | |
[ { even: 1, odd: 2 }, | |
{ even: 2, odd: 3 }, | |
{ even: 3, odd: 4 }, | |
{ even: 4, odd: 5 }, | |
{ even: 5, odd: 6 }, | |
{ even: 6, odd: 7 } ] | |
*/ | |
// | |
var pairs = nums.map(v => { | |
({even: v, odd: v + 1}) | |
}); // [ undefined, undefined, undefined, undefined, undefined, undefined ] | |
// Cannot use `()` if you want more than one statement inside the function | |
// var pairs = nums.map(v => | |
// var temp = 2 + v; | |
// ({even: temp, odd: temp + 1}) | |
// ); | |
// NOTE: You have to use `{}`, remove the `()` and add the return keyword | |
var pairs = nums.map(v => { | |
var temp = 2 + v; | |
return {even: temp, odd: temp + 1} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment