Sometimes I get hit by random thoughts in the middle of some programming changes. Have you ever wanted to write code like this?

`for (var i in range(12)) ...`

or:

`for (var i in range(-10,11,5)) ...`

More likely than not, somebody else has already tried this, but I couldn’t find any implementations. Just to prove that it’s possible–and with *no* regard to efficiency–here’s the magic function:

function range(/*[start,] stop[, step]*/) { if (!arguments.length) { return []; } var min, max, step; if (arguments.length == 1) { min = 0; max = arguments[0]-1; step = 1; } else { /* default step to 1 if it's zero or undefined */ min = arguments[0]; max = arguments[1]-1; step = arguments[2] || 1; } /* convert negative steps to positive and reverse min/max */ if (step < 0 && min >= max) { step *= -1; var tmp = min; min = max; max = tmp; min += ((max-min) % step); } var a = []; for (var i = min; i <= max; i += step) { a[i] = i; } return a; }

Done. Back to work.

**Update:** I forgot to mention that negative steps return the correct values, but in the wrong order. Also, MochiKit provides a range function but the results can only be iterated with library functions and cannot be iterated with the *for* keyword.