Javascript Rest and Spread Operators

JavaScript Rest & Spread Operators

Rest and Spread operators in Javascript will help you work with arrays and save you some typing. See the inline comments below for context.

USAGE: Copy and paste the code samples below into the Javascript console in your browser, then simply hit return on your keyboard to see the code in action.

//Rest operator
//The 3 dots before the passed reference name tells the function to create an array of whatever gets passed to it
function sumUp(...toAdd) {
  console.log(toAdd);
  let result = 0;
  for (i = 0; i < toAdd.length; i++) {
    result += toAdd[i];
  }
  return result;
}
console.log(sumUp(100, 10, "20"));


//Spread operator (opposite to the Rest operator)
let numbers = [1, 2, 3, 4, 5];
//the 3 dots allows the max method to receive an array instead of a list
console.log(Math.max(...numbers));


Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/javascript/javascript-rest-and-spread-operators/
Copyright 2019. All Rights Reserved.