paint-brush
JavaScript Spread and Rest Operators: A Guideby@gerald-goh
10,933 reads
10,933 reads

JavaScript Spread and Rest Operators: A Guide

by Gerald GohMarch 1st, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. 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.
featured image -  JavaScript Spread and Rest Operators: A Guide
Gerald Goh HackerNoon profile picture

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]; 


Alternatively, the spread can be used in objects


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.