Rest operator vs spread operator in javascript

Sahil Ali
1 min readFeb 19, 2024

--

In JavaScript, the ... operator is called the "spread" operator or the "rest" operator, depending on how it's used.

Photo by Shahadat Rahman on Unsplash

JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same.

  1. Spread Operator (...):

When used in function calls or array literals, it allows an iterable (like an array or a string) to be expanded into individual elements. For example:

const array1 = [1, 2, 3]; 
const array2 = [...array1, 4, 5, 6]; // array2 is [1, 2, 3, 4, 5, 6]

2. Rest Parameter (...):

When used in function parameters, it collects all remaining(rest of) arguments into an array. For example:

function sum(...numbers) {    
return numbers.reduce((total, num) => total + num, 0); }
console.log(sum(1, 2, 3, 4)); // Output: 10

In both cases, the ... operator facilitates concise and flexible code by spreading or collecting elements or parameters.

Tags

Rest operator vs spread operator in javascript
Rest operator vs spread operator in javascript examples
Rest operator vs spread operator in javascript array
rest operator in javascript
rest operator javascript
rest and spread operator in javascript with example
rest operator example
rest operator in es6

--

--

Sahil Ali

SDE || Exploring New Technologies & Science || Useful Website & AI Tools || Resolving Error | https://www.linkedin.com/in/sahilali20/