If you have any experience with JavaScript, you ought to know that function arguments are accessible via an implicit array-like object called arguments. This method of argument access allows variable-length argument lists:
function sum() {
var sum = 0, len = arguments.length;
for (var i = 0; i < len; i++)
sum += arguments[i];
return sum;
}
How do named arguments interact with implicit arguments? I won’t answer this question for you, but by way of clarification I pose the following puzzles.
What do each of these expressions evaluate to?
(function(x, y) { x = y; return arguments[0] })(1, 2)
(function(x, y) { arguments[0] = y; return x })(1, 2)
Variations on a more complicated theme:
(function(x) {
var args = arguments;
return (function(y) {
x = y;
return args[0];
})(2);
})(1)
(function(x) {
var args = arguments;
return (function(y) {
x = y;
return args;
})(2)[0];
})(1)
(function(x) {
var args = arguments;
return (function(y) {
x = y;
return args;
})(2);
})(1)[0]
(function(x) {
var args = arguments;
return function(y) {
x = y;
return args[0];
};
})(1)(2)
(function(x) {
var args = arguments;
return function(y) {
x = y;
return args;
};
})(1)(2)[0]
Some of these expressions do not evaluate to 2. Can you spot the reason?

Leave a comment