The if-else
and switch
statements allow your code to take different paths, as if you're at a crossroad and decide which way to go depending on a condition. Loops, on the other hand, allow your code to take a few roundabouts before merging back into the main road. How many repetitions? That depends on the result of evaluating a condition before (or after) each iteration.
Let's say you are (your program execution is) traveling from A to B. At some point, you reach a place where you evaluate a condition, C. The result of evaluating C tells you if you should go into a loop, L. You make one iteration and arrive at C again. Then, you evaluate the condition once again to see if another iteration is needed. Eventually, you move on your way to B.
An infinite loop is when the condition is always true
and your code gets stuck in the loop "forever". This is, of course, a logical error, and you should look out for such scenarios.
In JavaScript, there are four types of loops:
while
loopsdo-while
loopsfor
loopsfor-in
loops
while
loops are the simplest type of iteration. They look like this:
var i = 0; while (i < 10) { i++; }
The while
statement is followed by a condition in parentheses and a code block in curly brackets. As long as the condition evaluates to true
, the code block is executed over and over again.
do-while
loops are a slight variation of while
loops. An example is shown as follows:
var i = 0; do { i++; } while (i < 10);
Here, the do
statement is followed by a code block and a condition after the block. This means that the code block is always executed, at least once, before the condition is evaluated.
If you initialize i
to 11
instead of 0
in the last two examples, the code block in the first example (the while
loop) will not be executed, and i
will still be 11
at the end, while in the second (the do-while
loop), the code block will be executed once and i
will become 12
.
for
is the most widely used type of loop, and you should make sure you're comfortable with this one. It requires just a little bit more in terms of syntax.
In addition to the condition C and the code block L, you have the following:
0
in the diagram)++
in the diagram)The most widely used for
loop pattern is:
i
i
to a boundary value, like i < 100
i
by 1
, like i++
Here's an example:
var punishment = ''; for (var i = 0; i < 100; i++) { punishment += 'I will never do this again, '; }
All three parts (initialization, condition, and increment) can contain multiple expressions separated by commas. Say you want to rewrite the example and define the variable punishment
inside the initialization part of the loop:
for (var i = 0, punishment = ''; i < 100; i++) { punishment += 'I will never do this again, '; }
Can you move the body of the loop inside the increment part? Yes, you can, especially as it's a one-liner. This gives you a loop that looks a little awkward, as it has no body. Note that this is just an intellectual exercise; it's not recommended that you write awkward-looking code:
for ( var i = 0, punishment = ''; i < 100; i++, punishment += 'I will never do this again, ') { // nothing here }
These three parts are all optional. Here's another way of rewriting the same example:
var i = 0, punishment = ''; for (;;) { punishment += 'I will never do this again, '; if (++i == 100) { break; } }
Although the last rewrite works exactly the same way as the original, it's longer and harder to read. It's also possible to achieve the same result by using a while
loop. But, for
loops make the code tighter and more robust because the mere syntax of the for
loop makes you think about the three parts (initialization, condition, and increment), and thus helps you reconfirm your logic and avoid situations such as being stuck in an infinite loop.
The for
loops can be nested within each other. Here's an example of a loop that is nested inside another loop and assembles a string containing 10 rows and 10 columns of asterisks. Think of i
being the row and j
being the column of an "image":
var res = ' '; for (var i = 0; i < 10; i++) { for (var j = 0; j < 10; j++) { res += '* '; } res += ' '; }
The result is a string like the following:
" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "
Here's another example that uses nested loops and a modulo operation to draw a snowflake-like result:
var res = ' ', i, j; for (i = 1; i <= 7; i++) { for (j = 1; j <= 15; j++) { res += (i * j) % 8 ? ' ' : '*'; } res += ' '; }
The result is:
" * * * * * * * * * * * * * * * * * "
The for-in
loop is used to iterate over the elements of an array (or an object, as you'll see later). This is its only use; it cannot be used as a general-purpose repetition mechanism that replaces for
or while
. Let's see an example of using a for-in
to loop through the elements of an array. But, bear in mind that this is for informational purposes only, as for-in
is mostly suitable for objects, and the regular for
loop should be used for arrays.
In this example, you iterate over all of the elements of an array and print out the index (the key) and the value of each element:
// example for information only // for-in loops are used for objects // regular for is better suited for arrays var a = ['a', 'b', 'c', 'x', 'y', 'z']; var result = ' '; for (var i in a) { result += 'index: ' + i + ', value: ' + a[i] + ' '; }
" index: 0, value: a index: 1, value: b index: 2, value: c index: 3, value: x index: 4, value: y index: 5, value: z "
3.142.119.241