Created
May 5, 2016 22:17
-
-
Save santiago-puch-giner/3b448d7ede09a1de7dfff8e8402ee59b to your computer and use it in GitHub Desktop.
Rest parameters and spread operator in Javascript (ES6)
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
// Snippet for rest parameters and spread operator (ES6) | |
// Rest parameters allow you to capture and indefinite number of parameters | |
// passed to a function | |
let sum = function(...args) { | |
// args is an Array with the parameters | |
return args.reduce( (prev, curr) => prev + curr); | |
} | |
console.log(sum(1, 1, 1, 1, 3)) // 7 | |
let scaleNums = function(scale, ...nums) { | |
return nums.map( (n) => scale * n); | |
} | |
console.log(scaleNums(2, 3, 4, 5, 6)) // [6, 8, 10, 12] | |
// Spread operator lets you "spread" an array into its individual elements | |
var myArray = [1, 2, 3]; | |
var mySecondArray = [...myArray, 4, 5, 6]; | |
console.log(...myArray); // 1 2 3 | |
console.log(mySecondArray); // [1, 2, 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment