Home »
JavaScript
Rest Operator in JavaScript
JavaScript rest Operator: Here, we are going to learn about the rest operator in JavaScript with example.
Submitted by Siddhant Verma, on November 02, 2019
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.
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);
Output
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.
function display(...arr) {
console.log(arr);
arr.forEach(e => {
console.log(e);
})
console.log(typeof(arr));
}
display(1, 2, 3, 4, 5);
Output
(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.
Note: 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);
})
}
Output
Uncaught SyntaxError: Rest parameter must be last formal parameter
function show(name, ...args) {
console.log('Name: ', name);
args.forEach(arg => {
console.log(arg);
})
}
show('Fuzzy', 0, 5, 10);
Output
Name: Fuzzy
0
5
10
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);
Output
{name: "Player1", Health: 100}
JavaScript Tutorial »