Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A for loop without any {}

Tags:

javascript

So I was reading about shuffling an array. And then I came across this script:

shuffle = function(o){ //v1.0
    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;
};

When I look closely, the for does not even have any {} at all! But it is working, like magic. I am very curious to know how it work. (and the bunch of commas too.)

like image 565
Derek 朕會功夫 Avatar asked Jun 13 '12 03:06

Derek 朕會功夫


2 Answers

What follows the for () can be any statement; that can be something with curly braces, or it can be a single expression, or it can be an empty expression. for (...); is equivalent to for (...) {}. Naturally, this should only be used in conjunction with a for-loop which will terminate naturally, or you'll have an infinite loop on your hands.

The commas are effectively second-grade semicolons; they make for mostly-separate statements, but which will work in a for loop (and elsewhere; this is a very sloppy definition of them).

for (
     // initialisation: declare three variables
     var j, x, i = o.length;
     // The loop check: when it gets to ``!i``, it will exit the loop
     i;
     // the increment clause, made of several "sub-statements"
     j = parseInt(Math.random() * i),
     x = o[--i],
     o[i] = o[j],
     o[j] = x
)
    ; // The body of the loop is an empty statement

This could be put in a more readable form as:

for (
     // initialisation: declare three variables
     var j, x, i = o.length;
     // The loop check: when it gets to ``!i``, it will exit the loop
     i;
     // note the increment clause is empty
) {
     j = parseInt(Math.random() * i);
     x = o[--i];
     o[i] = o[j];
     o[j] = x;
}

As a while loop, that could be:

var j, x, i = o.length;
while (i) {
     j = parseInt(Math.random() * i);
     x = o[--i];
     o[i] = o[j];
     o[j] = x;
}
like image 83
Chris Morgan Avatar answered Sep 24 '22 17:09

Chris Morgan


Every computing is in same statement for single statement we dont need {} but also in this statement ; (sentence terminator is used in the end) it means next statement does not belong to for statement. Whatever logic is it is in same for statement.

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


  for(var j, x, i = o.length;// Initialization
  i;// Work until i is zero
 j = parseInt(Math.random() * i),
  x = o[--i], o[i] = o[j], o[j] = x);//Here he is    computing his logic
like image 44
Amritpal Singh Avatar answered Sep 26 '22 17:09

Amritpal Singh