Home »
JavaScript
JavaScript Rest Operator (with Example)
JavaScript Rest Operator: In this tutorial, we will learn about the rest operator in JavaScript with the help of examples.
By Siddhant Verma Last updated : July 29, 2023
JavaScript Rest Operator
The rest operator was introduced by ES6 and looks something like this ...
Wait am I talking about the spread operator? Well, both rest and spread operators are the same but they're not essentially the same thing. We use...
As both spread and rest operator in JavaScript and they both perform differently or precisely the opposite functions. The operator is simply overloaded for rest and spread both. In this article, we'll talk about how and where to use rest operators in Javascript and eventually differentiate it from the spread operator.
In case you're unfamiliar with the spread operator, have a quick read here on what spread operators is, how and where to use it.
The spread operator would expand items of an iterable, the rest, on the other hand, collects them together.
Example without rest
function add(...arr) {
let ans = 0;
for (let a of arr) {
ans += a;
}
console.log(ans);
}
add(1, 2, 3, 4, 5);
add(1, 2);
add(23, 43, -11);
The output of the above example is:
15
3
55
We pass individual numbers as arguments and group them using the rest operator or the rest parameter.
The rest parameter gives us an array so an essential use case would be where we have to implement certain functionality on certain values as a single entity. For example, using array methods like forEach on individual items.
Example with rest
function display(...arr) {
console.log(arr);
arr.forEach(e => {
console.log(e);
})
console.log(typeof(arr));
}
display(1, 2, 3, 4, 5);
The output of the above example is:
(5) [1, 2, 3, 4, 5]
1
2
3
4
5
object
Thus we get an object which is just an object wrapper around an array and we can use all our usual array methods on this object wrapped around an array.
What happens, if the rest parameter is not last formal parameter
While using the rest parameter, ensure that it is the last parameter to be passed to a function otherwise an error will occur.
function show(...args, name) {
console.log('Name: ', name);
args.forEach(arg => {
console.log(arg);
})
}
The output of the above example is:
Uncaught SyntaxError: Rest parameter must be last formal parameter
What happens, if the rest parameter is last formal parameter
function show(name, ...args) {
console.log('Name: ', name);
args.forEach(arg => {
console.log(arg);
})
}
show('Fuzzy', 0, 5, 10);
The output of the above example is:
Name: Fuzzy
0
5
10
Rest parameter for destructuring
We can also use the rest parameter for destructuring to obtain remaining properties and store them in an object.
const player= {
id: 1, name: 'Player1', Health: 100
}
;
const {
id,
...rest
}=player;
console.log(rest);
The output of the above example is:
{name: "Player1", Health: 100}
JavaScript Tutorial »