Rest and Spread Operator in JavaScript

Shubham Gupta
3 min readJul 10, 2023

--

Rest and Spread operators use (…) three dots but are not the same.

Rest Operator

The operator is used to put some user-supplied values into an Array. The text after the rest operator references the values you wish to encase inside an array. You can only use it before the last parameter in a function definition.

Example

function sumAll(...args) {
// args is the name for the array
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
// here the function can be called with any number of arguments
sumAll(1)
sunAll(1,2,3)

We can choose to get the first parameters as variables, and gather only the rest.

function showName(firstName, lastName, ...titles) {
alert( firstName + ' ' + lastName ); // Julius Caesar
// the rest go into titles array
// i.e. titles = ["Consul", "Imperator"]
alert( titles[0] ); // Consul
alert( titles[1] ); // Imperator
alert( titles.length ); // 2
}

showName("Julius", "Caesar", "Consul", "Imperator");

// If we access the arguments object from an arrow function,
// it takes them from the outer "normal" function.

Note: The Rest parameter should always be at the end in the parameter list, else it causes an error.

There is also a special array-like object named arguments that contains all arguments by their index. But the downside is that although arguments is both array-like and iterable, it’s not an array. It does not support array methods, so we can’t call arguments.map(...) for example. Also, it always contains all arguments. We can’t capture them partially, like we did with rest parameters. So when we need these features, then rest parameters are preferred.

You Cannot Use “use strict” Inside a Function Containing a Rest Parameter,otherwise, the computer will throw syntax Error.

Rest operator as destructing assignment

The rest operator typically gets used as a prefix of the destructuring assignment’s last variable.

Example

// Define a destructuring array with two regular variables
// and one rest variable:
const [firstName, lastName, ...otherInfo] = [
"Naruto", "Sasuke", "Goku", "Ichigo", "Kirito"
];

// Invoke the otherInfo variable:
console.log(otherInfo);

// The invocation above will return:
["Goku", "Ichigo", "Kirito"]

Spread Operator

while using rest operator we make an array of parameters , but sometimes we need to the exact opposite and extract all the values , this is where we use spread operator

The spread syntax works within array literals, function calls, and initialized property objects to spread the values of iterable objects into separate items. So effectively, it does the opposite thing from the rest operator.

let arr = [3, 5, 1];
alert( Math.max(...arr) );

We can even combine the spread syntax with normal values:

let arr1 = [1, -2, 3, 4];
let arr2 = [8, 3, -8, 1];
alert( Math.max(1, ...arr1, 2, ...arr2, 25) );

Can also be used to convert String into array of characters

let str = "Hello";
alert( [...str] ); // H,e,l,l,o

Copying an Array/Object

let obj = { a: 1, b: 2, c: 3 };

let objCopy = { ...obj }; // spread the object into a list of parameters
// then return the result in a new object

// do the objects have the same contents?
alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true

Also while copying the value in nested is not deep copied it is shallow copied

Use patterns:

  • Rest parameters are used to create functions that accept any number of arguments.
  • The spread syntax is used to pass an array to functions that normally require a list of many arguments.

If you’d like to be in the know, subscribe, clap, like and share. Cheers!

--

--