Recently I got borred with the for loops and I added the “times” function on the prototype of Number. As a result, I can easily iterate over arrays or I can simply call a function how many times I want like this:

     (5).times(function(index /* zero based */){
           console.log(index);
     })
     //or using array length
     arr.length.times(function(){ ... });

     //optionally specify scope for the callback function:
    n.times(function(){ .... }, scope);

Together with this, I’m using another goodie. Whenever I have a function that expects a parameter which can either be a simple value or an array, convert that value to array in one line, like:

    var arr = [].concat(valueOrArray);

See below the source code.

/**
 * extend the Number prototype
 * @param func
 * @param scope [optional]
 */
Number.prototype.times = function(func, scope){
    var v = this.valueOf();
    for (var i=0; i < v; i++){
        func.call(scope||window,i);
    }
};

function test(valueOrArray){
    var arr = [].concat(valueOrArray)
    arr.length.times(function(i){
        console.log(arr[i]);
    })
}

test([1,3,4])
//output: 1   3   4

test(123)
//output: 123

As for the performance, I have tested the times function against the for loop, and it seems to give about same results at a first glance. Any feedback on this?

P.S. Iterating over arrays gets even easier by adding an 'each' function to the Array prototype. Adding to the prototype of standard JavaScript objects is a debatable practice, and should not be abused.

Well, if you are programming in JavaScript for a while, you are familiar with the arguments ‘array’ which gives you access to function arguments by index, without the need of argument names. And if you are programming JavaScript for a bit longer while, you will know that arguments is not even a normal array. It does not have any methods of an array. You can just use it to access items by index and also access it’s length property. That’s all. What if you want to make a copy of the array? What if you want to push or pop items? Well… you have some work to do… OR …

Or do something smart. Like call the slice method from Array.prototype on the arguments, something like:

//this makes a copy of the arguments and returns a true array
Array.prototype.slice.call(arguments, 0) 

//pushes the value '5' in the arguments
Array.prototype.push(arguments, 5) 
//this is not valid: arguments.push(5)

Well, maybe most of you expert JavaScript programmers have thought about this, and this is not a news. But, let’s share from our experience to the more novice/newcomers to JavaScript and show them the beauty of this language!

JavaScript is a great language! It’s expressive! It’s powerful! That’s why we love JavaScript.