Arguments Object Parameters
Since JavaScript functions can be passed any number of parameters, it’s not always necessary to define each parameter specifically. Early on, JavaScript provided the arguments object as a way of inspecting all function parameters that were passed without necessarily defining each one individually.
Rest Parameters
The rest parameter syntax allows to represent an indefinite number of arguments as an array.
Arguments Object Parameter Example
function pick(object) {
let result = Object.create(null);
for (let i = 1, len = arguments.length; i < len; i++) {
result[arguments[i]] = object[arguments[i]];
}
return result;
}
let book = {
title: "Understanding ECMAScript 6",
author: "Nicholas C. Zakas",
year: 2015
};
let bookData = pick(book, "author", "year");
console.log(bookData.author); // "Nicholas C. Zakas"
console.log(bookData.year); // 2015
Rest Parameters Example
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
Difference 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).
No comments:
Post a Comment