Iterating Arguments in JavaScript

A correct way to iterate arguments in JavaScript. This is a short snippet that most of you are aware of, but it is nice to note it because if you don’t know it you will get into problems like me, a year ago.
We all do development in one of the browsers, and then we test it in others to check for compatibility. Sometimes we believe that basic things are standardized in all of them. Like to falsely presume that you can iterate arguments with for(var i in arguments), because arguments is an object like array but without length. And then you build a big class or several classes where you iterate arguments that way and you decide to test it in other browsers… And something doesn’t work, and you don’t know what, nor where to start debugging because it returns no errors.

The thing is that arguments in an object of Arguments class [object Arguments] and that class cannot be prototyped because it is not global. Also Arguments object behaves as an array having length property and enumerable values starting from 0, but it is an object. The specification of JavaScript 1.1 and further claims that length property of an arguments object should always be available, so that means the correct and obvious way to do the iteration is through loops like for(var i = 0; i < arguments.length; i++) or while(i < arguments.length).

So I created a simple function to aid myself whenever I need to pass through arguments or some of the arguments.
The parameters for this method are: arguments (mandatory, ofc :)), function that executes on each argument with passed arguments of argument id and value, start from what argument id and last end on what argument id so you can precisely set the subset of arguments you want to iterate.


var eachArg = function(args, fn, start_from, end_where) {
var i = start_from || 0;
while (i < args.length) {
if (end_where !== undefined && i === end_where)
return i;
if (fn !== undefined)
fn(i, args[i]);
i++;
}
return i;
};

If you don’t pass the last argument to the function above it returns the length of arguments.

Here is a simple example of usage:

function fn(i, val) {
    console.log(i+': '+val);
}

function func() {
    return eachArg(arguments, fn);
}

function func1() {
    eachArg(arguments, fn , 2);
}

function func2() {
    eachArg(arguments, fn, 1, 3);
}

console.log(func('a','b','c','d','e','f'));
/* prints out:
    0: a
    1: b
    2: c
    3: d
    4: e
    5: f

    and lastly : 6
*/

func1('a','b','c','d','e','f');
/* prints out:
    2: c
    3: d
    4: e
    5: f
*/

func2('a','b','c','d','e','f');
/* prints out:
    1: b
    2: c
*/

Hope it’s useful! :)

Leave a comment