views:

209

answers:

4

So I took a look at the code that controls the counter on the SO advertising page. Then I saw the line where this occured i-->. What does this do?

Here is the full code:

$(function(){

    var visitors = 5373891;
    var updateVisitors = function()
    {
            visitors++;

            var vs = visitors.toString(), 
                 i = Math.floor(vs.length / 3),
                 l = vs.length % 3;
            while (i-->0) if (!(l==0&&i==0))          // <-------- Here it is!!!
                vs = vs.slice(0,i*3+l)
                   + ',' 
                   + vs.slice(i*3+l);
            $('#devCount').text(vs);
            setTimeout(updateVisitors, Math.random()*2000);
    };

    setTimeout(updateVisitors, Math.random()*2000);

});
+12  A: 

i-->0 is the same as i-- > 0, so the comparison expression if the evaluated value of i-- is greater than 0.

Gumbo
Wow, running it all together like that even confused me for a moment there. Good eye, Gumbo.
Jonathan Sampson
That seems really messy! Thanks for explaining it.
Bob Dylan
Just to clarify, means that the comparison "i > 0" occurs *before* i is decremented.
Rob Levine
its basically `(i-1) > 0` :)
RobertPitt
+6  A: 

it is not an operator. See this link:

http://stackoverflow.com/questions/1642028/what-is-the-name-of-this-operator

var i = 10;

while (i-- > 0)
{
   alert('i = ' + i);
}

Output:

i = 9 
i = 8 
i = 7 
i = 6 
i = 5 
i = 4 
i = 3 
i = 2 
i = 1 
i = 0
JCasso
Did you mix C# with your Java? ;-)
Bob Dylan
At first i thought that i wrote the javascript code wrong :) You mean the avatar. Yes I migrated C# from Java and i love coffee :)
JCasso
A: 

Thought of the exact same thread that JCasso thought of. http://stackoverflow.com/questions/1642028/what-is-the-name-of-this-operator

I think this code style stems from the early days of programming when terminals had limited display real estate.

creminsn
No, it's quite a new trend. It's syntactic sugar that reads `while i approaches zero`. Some people like it. Some just gets confused. It really depends on weather you've gotten used to seeing it or not. Kinda like regular expressions: when you first see it you want to vomit violently onto the keyboard, then you grow to love it.
slebetman
Ahh ok, you learn something new everyday. I'm not a huge fan of it I have to admit i-- > 0 reads better to me.
creminsn
I appreciate the `-->` operator, but no number of years of regex use has stopped me vomiting :-)
bobince
A: 

Other answers have explained that it's two operators. I'll just add that in the example, it's unnecessary. If you're counting down from a positive integer to zero, you can miss out the greater-than-zero test and your code will be shorter and, I think, clearer:

var i = 10;
while (i--) {
    // Do stuff;
}
Tim Down