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 */){
     //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++){||window,i);

function test(valueOrArray){
    var arr = [].concat(valueOrArray)

//output: 1   3   4

//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.

2 thoughts on “No for loops – Number prototype instead

  1. ExtJS already implements such functionality. It would also be useful to write a similar function for iterating object properties.
    See Ext.each and Ext.iterate

  2. @Dmitriy You are right, Ext provides nice iteration methods. I just wanted to point out a short intro to this issue, that can be used standalone, without all the overhead that ExtJS brings. I admit it’s nothing new :) Thanks for following and for the comment.

Leave a reply


<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>