Javascript – Regarding JavaScript for() loop voodoo


I was for quite some time under the impression that a for loop could exist solely in the following format:


This is, however, most definitely not the case; take a look at this JavaScript implementation of the Fisher-Yates Shuffle:

shuffle = function(o)
    for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;

This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean… it doesn't even open a brace! All of the magic is being done right there inside the for statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.

Best Solution

The generalized format of a for loop (not a for-in loop) is


The first EXPRESSION_1 is usually used to initialize the loop variable, EXPRESSION_2 is the looping condition, and EXPRESSION_3 is usually an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:

while (EXPRESSION_2) {

The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:

shuffle = function(o) {
    var j, x;
    for (var i = o.length; i > 0; i--) {
        j = parseInt(Math.random() * i);
        x = o[i - 1];
        o[i - 1] = o[j];
        o[j] = x;
    return o;