Loops are real menaces! The vast majority of browser crashes are caused by badly constructed JavaScript loops. – I don’t have any numbers to back this up but I think it seems like a pretty reasonable statement. Even if loops aren’t the number #1 cause they’re probably still pretty near the top.
You can see how much is at stake here; constructing a loop incorrectly can leave a browser fighting for breath, so it’s a good idea to learn the basics before you go trotting off in the wrong direction.
The WHILE statement
This is probably my favourite statement in JavaScript, and it’s probably the most useful one you’ll ever come across.
It’s pretty simple too: as long as the passed condition evaluates to true the statement will continue to execute over and over again, it will only stop when the condition evaluates to false. Here’s a pretty cool example: say we want to remove all child nodes of the ‘body’ element; you might think building up a collection of elements and then removing each one is the best technique but there is an even simpler approach:
var body = document.body; while (body.firstChild) { body.removeChild(body.firstChild); }
The statement will be executed as long as the body node has a ‘firstChild’ – when there are no child nodes left the condition will no longer be met and so the statement will not be executed. Note that you don’t have to include the curly braces to surround a single-line statement; I just think it looks nicer…
Traversing through a regular array can also be achieved using the WHILE loop. There are two well-known methods, one iterating in order, and one going backwards through the array:
// #1 : regular var myArray = ['apple','orange','lemon'], length = myArray.length, counter = 0; while (counter < length) { alert ( myArray[counter] ); counter++; } // alerts 'apple', then 'orange', then 'lemon' // #2 : in reverse var myArray = ['apple','orange','lemon'], length = myArray.length; while (length--) { alert ( myArray[length] ); } // alerts 'lemon', then 'orange', then 'apple'
The first type is quite simple, the ‘counter’ variable increments by one every time the statement is run. So when the counter is no longer smaller than the array’s length (3) the statement will STOP running.
The second type doesn’t require a ‘counter’; it just decrements (by one) the value of ‘length’ every time the statement runs, and eventually it will be down to 0 (zero) which is a false-evaluating value and will therefore stop the condition from being met.
Performance:
It’s been tested: looping through a set of DOM elements or any array for that matter, using a reverse while loop is faster than any of the other well-known alternatives (e.g. a standard FOR loop).