DEV Community

SCDan0624
SCDan0624

Posted on

4 2

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay