JavaScriptFundamental (ES6), part 1
Sum any number of arguments with rest in JavaScript
9 Rest parameters instead of arguments
fairSum any number of arguments twice: once with arguments and once with a rest parameter. Then show what arguments means inside an arrow nested in a normal function.
Stuck? Three hints, smallest first
- 1.
argumentsis array-like: it has alengthand indexes, but none of the array methods. - 2. A rest parameter is a real array, so
reduceworks on it directly. - 3. An arrow has no
arguments. Reading it inside one finds the enclosing function’s.
function classic() {
return Array.prototype.slice.call(arguments).reduce((a, b) => a + b, 0);
}
const modern = (...ns) => ns.reduce((a, b) => a + b, 0);
function grab() { return arguments; }
const grabRest = (...xs) => xs;
function outerArguments() {
const peek = () => arguments.length; // the outer function's, not its own
return peek();
}
function bothKinds() {
const peek = (...own) => ({ own: own.length, outer: arguments.length });
return peek('x');
}
function withDefault(a, b = 2) { return arguments.length; }
console.log('classic(1, 2, 3) :', classic(1, 2, 3));
console.log('modern(1, 2, 3) :', modern(1, 2, 3));
console.log('arguments is an array?', Array.isArray(grab(1, 2)), ' rest is?', Array.isArray(grabRest(1, 2)));
console.log('arrow inside a function sees', outerArguments(1, 2, 3), 'arguments');
console.log('both at once :', bothKinds(1, 2, 3));
console.log('withDefault(1) :', withDefault(1), '<- counts what was passed');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain function has an arguments object', classic(1, 2, 3), 6);
test('a rest parameter does the same job with less ceremony', modern(1, 2, 3), 6);
test('arguments is array-like, not an array', Array.isArray(grab(1, 2)), false);
test('a rest parameter is a real array', Array.isArray(grabRest(1, 2)), true);
test('arguments is iterable, so spread converts it', [...grab(1, 2)], [1, 2]);
test('an arrow has no arguments, so it reads the enclosing one', outerArguments(1, 2, 3), 3);
test('its own rest parameter is separate from that', bothKinds(1, 2, 3), { own: 1, outer: 3 });
test('arguments counts what was passed, not what was declared', withDefault(1), 1);
Array.prototype.slice.call(arguments) was boilerplate in every utility function written before 2015. A rest parameter replaces it with something that is already an array, is named, and shows up in the signature where a reader will look.
The nesting assertion is the subtle one. An arrow inside a function does not shadow arguments, so outerArguments reports three — occasionally handy, more often a surprise. If you want the arrow's own list, give it a rest parameter and the two never collide.