JavaScript Rest vs Spread Operator

Akshay Waingankar
3 min readJan 22, 2023

Rest and spread operators were introduced in the es6 version of JavaScript. In the previous version i.e es5, we are dealing with arguments. Both look quite similar as both have common syntax (…) but work exactly opposite to each other. Let's see the difference between this operator and when to use what.

Rest vs Spread Operator

Rest Operator

It is an array of elements and is used at the end of the parameter list. It will create an array from separate elements.

function restFunction(a,b, ...restElement){
console.log(a,b);
console.log(restElement);
}
restFunction(5,6,7,8,9,10);

//Output
5, 6
[7, 8, 9, 10]

In the above function, first two elements were captured in a, b parameters list and the rest of the parameters will wrap inside rest restElement as an array.

Let's check with the object

let details = {
firstName : "ABC",
lastName :"XYZ",
age : 22,
address : {
city : "Mumbai",
state : "Maharashtra"
}
}

let {age, ...restDetails} = details;
console.log(age);
console.log(restDetails);

//Output
22
{
address: {
city: "Mumbai",
state: "Maharashtra"
},
firstName: "ABC",
lastName: "XYZ"
}

In object destruction, we are fetching age property and remaining properties wrap inside restDetails object.

Spread Operator

It is spreading array values into separate elements. So array can be iterated using the spread operator.

let array = [8,9,10];
for(let a of array){
console.log(a);
}

//Output
8
9
10

With string

let string = "Hello";
console.log(...string)

//Output
"H", "e", "l", "l", "o"

Combining two arrays with spread operator

let arrayOne = [1,2,3];
let arrayTwo = [6,7];
let resultArray = [...arrayOne, 4,5, ...arrayTwo]
console.log(resultArray);

//Output
[1, 2, 3, 4, 5, 6, 7]

Difference

Rest vs Spread

Thanks for reading

You can check my other articles as well. List is below.

Happy coding 😃

--

--