Console Learner — An interactive JavaScript course.


3.6 Variadic Functions

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


  
>>>
test(1, 2, 3)
[1, 2, 3]
The special variable arguments contains all the function call arguments. It is an Array-like object that can be accessed like a normal Array.
>>>
function add() {
    var res = 0;
    for (var arg of arguments) {
        res += arg;
    }
    return res;
}


  
>>>
add(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 tail() {
    return arguments.slice(1);
}


  
>>>
tail(1, 2, 3)
TypeError: arguments.slice is not a function. (In 'arguments.slice(1)', 'arguments.slice' is undefined)
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.
>>>
var tail2 = (...args) => args.slice(1);


  
>>>
tail2(1, 2, 3)
[2, 3]
The newer ...var rest parameters syntax (since ES6 in 2015) does away with the arguments variable. Instead, additional arguments are provided in a normal Array.
>>>
var tail3 = (first, ...others) => others;


  
>>>
tail3(1, 2, 3)
[2, 3]
The new syntax supports both declared and variable arguments. Of course, there can be only one rest parameter and it has to go at the end.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.