Spread & Rest Operators

Balaji Ashok Kumar
2 min readDec 3, 2018

--

Spread & Rest

ECMAScript 6 introduced Spread and Rest operators which can make our code cleaner and clearer.

Actually, it’s only one operator three dots (…). Yes, this may look strange but the operator is just three dots! Whether we call it spread or rest depends on where we use it.

Spread Operator

Spread operator is used to split up array elements or object properties. So, in easy words, we are spreading up an array or object with this operator.

For eg, if we have an old array and want to copy its content to a new array and additionally add new elements to that new array. Then we can achieve this by adding three dots in-front of old array like given below.

let newArray = [...oldArray, 3, 6];

This applies same for objects too, where we will create new object with curly braces as given below.

let newObject = {...oldObject, newProp: 6};

You can check the Spread operator in action in below CodePen.

Spread Operator

Rest Operator

Rest operator is used to merge a list of function arguments into an array.

Here is an example, sortInputs receives an unlimited number of arguments. So one argument, two, three or many more, with three dots we only write one argument args but we may actually receive more than one and they all will be merged together into an array.

You can check the Rest operator in action in below CodePen.

Rest Operator

Like this?

Hit the clap button 👏👏🏻👏🏼👏🏽👏🏾👏🏿 (as many times as you want!) :)

Please feel free to share your feedback and I would very much welcome it :) Thanks for reading. Have a nice day!!!

--

--