JavaScript 101 - Loops
Repetitive tasks suck! Loops help us automate repetitive tasks by performing some specified action until an exit condition is met. Loops come in two different flavors, entry loops and exit loops.
Entry Loops
Entry loops check for the exit conditions before it does the action.
var i = 0;
var elementList = document.querySelectorAll('.loopResults li');
while( i <= 3 ) {
elementList[i].style.backgroundColor = "green";
i++;
}
Run Reset
Results:
-
-
-
-
While()
The while()
loop is the basic entry loop. In the most simple terms it means: While the statement in the ()
evaluates to truey
it does whatever code is in the {}.
Example:
var i = 0;
while (i <= 16) { //Is the value of i greater than or equal to 16;
console.log(i);
i++; // Add one to i;
}
For()
The for()
loop is a specialized entry loop used when you know how many times you want to loop through it.
It includes a built in loop counter and var incrementation. The syntax is:
for ( counter variables ; Condition to evaluate ; do math to counter){
//Do Stuff here
}
Example:
for (i; i <= 16; i++ ) {
console.log(i);
}
Exit Loops
Exit loops check the conditional statement after it runs the code. This means that exit loops are always run at least once.
do{ … } while()
The do..while() loop
Example:
var i = 0;
do {
console.log(i);
i++; // Add one to i;
} while (i <= 16)
Special Loops
There are some special purpose loops that are available to handle common or special cases.
for(in)
Example:
var obj = {key1:1, key2:"two"};
for (var key in obj) {
console.log(key, obj[key]);
}
Bailing out of a Loop.
Sometimes you need to exit a loop before it is met it’s exit condition. There are a several of ways to do that.
Break
We were introduced to the break statement with the switch
. Break stops anything after the statement in the current scope {} and
jumps up one level of scope.
for (i=0;i<10;i++) {
if (i==3) break;
x=x + "The number is " + i + "<br>";
}
Return
Returns does basically the same thing as break but also can return a specified variable.
for (i=0;i<10;i++) {
if (i==3) return;
x=x + "The number is " + i + "<br>";
}
Continue
Continue overrides the one iteration of a loop.
for (i=0;i<=10;i++) {
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}