javascript interactive

JavaScript Interactive — a console crash course


3.6 Variadic Functions

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

At the moment this syntax is valid, but the next version of JavaScript includes a proposal for rest parameters which adds new syntax for variadic functions.

>>>
function test() {
    return arguments;
}

  
>>>
test(1, 2, 3)
[1, 2, 3]
The special variable arguments is available inside any function. It contains all the arguments from the function call and is an Array-like object that can be handled mostly like a normal Array.
>>>
function sum() {
    var res = 0;
    for (var i = 0; i < arguments.length; i++) {
        res += arguments[i];
    }
    return res;
}

  
>>>
sum(1, 2, 3, 4, 5)
15
Using the arguments array to create a variadic function (a function with variable number of arguments) is straight-forward.
>>>
function rest() {
    return arguments.slice(1);
}

  
>>>
rest(1, 2, 3)

  
But take note. The arguments variable is only Array-like, it is not a proper Array object. So it lacks most of its methods and general niceness.
>>>
(function () { return arguments.callee; })()

  
The special arguments.callee property is also sometimes useful, since it contains a reference to the function itself. This is practical for anonymous functions, that could otherwise not refer to themselves.
>>>

Index 1 2 3 4 5 6 7 8 9