DEV Community

SCDan0624
SCDan0624

Posted on

Javascript ES6 Rest/Spread

Rest
New to ES6 is the ability to pass in a variable number of arguments. These arguments are stored as array instances:

function myFunc(...args){
  return `You have passed in ${args.length} arguments`
}

myFunc(1,4,6,10,20) // You have pass in  5 arguments
Enter fullscreen mode Exit fullscreen mode

Since the arguments are stored as array instances we can use array methods directly on the arguments:

function myFunc(...args){
  let myArr = args
  let first = myArr.shift()
  return first
}


myFunc(1,4,7,10) // returns 1

Enter fullscreen mode Exit fullscreen mode

Spread
Also new to ES6 is the spread operator. Spread allows an iterable to expand in places where more than one argument is expected:

const myArr = [1,5,10]

const myArrTwo = [2,4,6, ...myArr]

console.log(myArrTwo) // [2,4,6,1,5,10]
Enter fullscreen mode Exit fullscreen mode

You can also use the spread operator to easily copy an array:

const myArr = [1,5,10,100,200]

const copyArr = [...myArr]

console.log(copyArr) //  [1,5,10,100,200]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)