Understanding the Spread and Rest syntax in Javascript

Ayelegun Michael Kayode
Backticks & Tildes
Published in
2 min readDec 21, 2018

The introduction of ES6 has been a delight to several javascript developers as it unlocks several features that make it easier to do complex computations. This article focuses on two of such features which are:

  • Spread syntax
  • Rest syntax
the three dots syntax. Credit: CodeBurst

Spread Syntax

“The spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.”

MDN documentation

Let’s say we have two arrays containing domestic and non-domestic animals.

and we need to combine two of them, we would normally use the concat array method.

Using the ES6 spread syntax, we could also write the above code like so:

These two lines of code both do the same thing, and the latter is known as the spread syntax. While generally, you would want to stick to using array methods when working with arrays, the advantage of using spread over concat can be seen in large operations where the spread operator is significantly faster. The spread syntax also enforces immutability, which is really important if you are working with data that should not be mutated. Basically, the spread syntax allows us to copy, into the new array, the values of already defined array(s).

Rest Syntax

Now, the rest 😁. The rest syntax follows the same convention as the spread syntax using the three dots before that which we choose to copy. But, the difference between the rest and spread syntax is that while spread copies everything, rest is used when we want to retrieve all remaining elements (or all existing elements) after a destructuring operation.

An example is shown below 👇

If you print out the value of the variable rest to the console, you’d get

['Moth', 'Sloth']

Also, say you had a function and you had no idea the number of arguments that would be passed to it, you could make use of rest parameters. An example would be a function that adds up the integers passed into it.

So, to recap, if you want to copy values of iterables(Objects/Strings/Arrays), make use of spread. If you want specific items to be excluded from the copy, make use of destructuring and the rest operator.

I hope you enjoyed reading this article as much as I enjoyed writing it. Follow me on twitter @stackless_dev or share your comments if you have a question you’d like me to answer.

--

--

Ayelegun Michael Kayode
Backticks & Tildes

Software engineer, 10 years exp. Tech enthusiast, lifelong learner, leader. Sharing insights on coding, leadership & tech philosophy.