Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Created May 5, 2016 22:17
Show Gist options
  • Save santiago-puch-giner/3b448d7ede09a1de7dfff8e8402ee59b to your computer and use it in GitHub Desktop.
Save santiago-puch-giner/3b448d7ede09a1de7dfff8e8402ee59b to your computer and use it in GitHub Desktop.
Rest parameters and spread operator in Javascript (ES6)
// 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