JavaScript Spread and Rest Operators: A Guide

Written by gerald-goh | Published 2023/03/01
Tech Story Tags: programming | javascript | es6 | js | javascript-tutorial | programming-tutorial | tutorial | beginners

TLDRSpread and Rest Operators are two of the most useful pieces of shorthand in JavaScript. Spread Operators allow us to expand an array or object into its individual elements. Rest Operator allows us to condense multiple elements into a single array. They’re extremely versatile tools, and every JavaScript programmer should know how to use them.via the TL;DR App

Spread and rest operators are two of the most useful pieces of shorthand in JavaScript. Spread operators allow us to expand an array or object into its individual elements, while rest operators allow us to condense multiple elements into a single array or object.

Spread operators are written using three consecutive dots (...), and they provide us with an easy way to break up an array or an object into its individual elements.

For example, let’s say we have the following array:

let array = [1, 2, 3, 4]; 

If we wanted to add a fifth element to our array, we could use the Spread Operator like this:

let newArray = [...array, 5]; 

The Spread Operator will take our array, expand it into its individual elements (1, 2, 3, 4), and then add the fifth element (5). The result is a new array that is one element longer than the original:

newArray = [1, 2, 3, 4, 5]; 

The rest operator is essentially the opposite of the spread operator. It collects multiple elements into an array. This is useful if you don’t know how many arguments a function may receive, and you want to capture all of them as an array.

The spread and rest operators are useful for quickly and easily manipulating collections and arguments. They make code much cleaner and easier to read, as well as reduce the number of lines of code needed.

They’re extremely versatile tools, and every JavaScript programmer should know how to use them.


Written by gerald-goh | A Developer who finds joy in combining the appeal of design with the complexity of engineering.
Published by HackerNoon on 2023/03/01