Tag Archives: loops

Javascript While Loop Decrement Explained

While watching Paul Irish : 10 Things I Learned from the jQuery Source, his code at the 31:30 mark looks like similar to this:

[cc]
var times = [42, 28, 75, 50, 62]
times = times[Math.floor(Math.random()*times.length)]

while (–times) {
do_something();
}
[/cc]

Not accustomed to seeing [cci]–[/cci], I wanted to research and explain what this snippet does. Paul’s code picks a random number in the [cci]times[/cci] array and runs [cci]do_something()[/cci] while [cci]times[/cci] is greater than 0.

The line by line breakdown looks like this:

[cc]
var times = [42, 28, 75, 50, 62]
[/cc]
Set the variable [cci]times[/cci] equal to an array of integers.
[cc]
times = times[Math.floor(Math.random()*times.length)]
[/cc]
Set [cci]times[/cci] equal to an integer chosen at random. [cci]Math.floor()[/cci] rounds down the integer. [cci]Math.random()[/cci] returns a random value between 0 and 1. [cci]times.length[/cci] returns the number of items in the [cci]times[/cci] array.
[cc]
while (–times) {
[/cc]
[cci]–times[/cci] runs the while loop while times is greater than zero. For instance, if times was 75, you can see that the while loop runs for the numbers 74 to 1, inclusive. Try it out in the JSFiddle.
[cc]
do_something();
[/cc]
[cci]do_something();[/cci] runs the function defined elsewhere.

Paul’s screencast is helpful, and diving into jQuery source is tremendously helpful.