Introduction:
There is an expression that says that good coders are lazy coders. This does not mean that coders are layabouts or bums. Rather, it means that the best coders can copy and paste code blocks, thus making their lives easier.
The same goes for blocks of code that repeat the same action over and over.
These code blocks are called loops
.
A loop
allows us to tell the computer to repeat an action until a condition is met.
It would be very tedious, for example, to write the following:
And writing the following will not repeat the action:
So how do we use loops
to repeat an action in Javascript
?
We use iteration
. In other words, we tell the code to iterate
through the code block until a condition is met:
Within this code block, we have 3 conditions:
i = 0;
:
This tells the code to start iterating at a specific index point, in this case at the first index, or index #0.
i < 3;
:
This tells the code to stop iterating after the specified number of loops have been actioned, in this case after 3 loops.
i++
:
This tells the code to increment by +1 after each run of the loop. We can also decrement by -1 by using i--
. Or, we can increment by specific values using
i = i + (x)
where (x) is the number to increment by.
The result of these 3 conditions mean that the alert "Hi" was repeated 3 times.
In JavaScript
there are a few ways to loop. We'll see those ways on the next page.