ES6 Spread/Rest Operator

ES6 has a handy feature called the Spread/Rest operator notated as .... The reason is has two names is because based on the use, it can do two different things.

Spread

For example, we can spread an array of values into a function parameters.

function myFunction(a, b, c) {
   console.log(a, b, c)
}

myFunction(...[1, 2, 3]) // outputs 1, 2, 3

We can aslo spread one array into another to improve array concatenation like so:

const a = [1, 2];
const b = [3, 4]'
const c = [...a, ...b];

console.log(c); // Results in [1, 2, 3, 4]

Rest

You can also use the operator to gather items into an array. A common usage of this is accepting extra arguments into a function

function myFunction(one, ...args) {
    console.log(args);
}

myFunction(1, 2, 3); // prints 1, [2, 3]

For more info, check the MDN docs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s