Rest parameters
The rest parameter syntax allows us to represent an indefinite number of arguments as an array with ...
prefix.
Basic usage
function student(name, ...marks) {
console.log(name); // myname
console.log(marks); // [10, 20, 30, 40, 50]
}
student('myname', 10,20,30,40,50);
In the above example, marks would collect the second argument of the function (because the first one is mapped to name) and all the consecutive arguments.
Difference between rest parameters and the arguments object
There are three main differences between rest parameters and the arguments object:
- rest parameters are only the ones that haven't been given a separate name, while the arguments object contains all arguments passed to the function;
- the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
- the arguments object has additional functionality specific to itself (like the callee property).
Working with arguments old way
function student(name, marks) {
console.log(name); // myname
console.log(arguments); // ["myname", 7, 4, 8, 2, 9]
console.log(marks); // 7
console.log(arguments.sort()); // Uncaught TypeError: arguments.sort is not a function(…)
}
student('myname', 7,4,8,2,9);
Es6 rest parameter implementation.
function student(name, ...marks) {
console.log(name); // myname
console.log(marks); // [7, 4, 8, 2, 9]
console.log(marks.sort()); // [2, 4, 7, 8, 9]
}
student('myname', 7,4,8,2,9);
Other usage example
function student(name, ...marks) {
console.log(name); // myname
console.log(marks); // [10, 20, 30]
var total = marks.reduce(function(a,b) {
return a+b;
})
console.log(total); // 150
}
student('myname', 10,20,30,40,50);