JavaScript Fundamentals: Mastering Loops
In JavaScript, we use loops when we want an easy way to handle repetition. In this article, we’re going to take a look at all the different ways we can create loops in our code — and we’ll consider the pros and cons of each method.
🤓 Want to stay up to date with web dev?
🚀 Want the latest news delivered right to your inbox?
🎉 Join a growing community of designers & developers!
Subscribe to my newsletter here → https://easeout.eo.page
A way to think of a loop could be to think of giving commands to a robot. You could tell it to take 10 steps — and rather than issuing 10 separate commands, we can create a loop:
let i;
for (i = 0; i < 10; i++) {
document.write("Take one step!\n");
}
This is an example of a for
loop. At first this may be confusing — but we’ll break it all down in the next section! In this article, we’ll be reviewing many different kinds of loop statements, such as: for
, do...while
, while
, labeled statement
, break statement
, continue statement
, for...in
& for...of
. It’s worth noting that despite their differences in syntax — loops all essentially do the same thing: repeat an action a number of times. The situation dictates which type of loop is best suited.
the for
loop
As we’ve seen in the above example, a for
loop will repeat until our condition evaluates to false. The logical structure is like so:
for ([initialExpression]; [condition]; [incrementExpression])
statement
We are first initializing the initialExpression
, which usually initializes one or more loop counters, but the syntax even allows for more complex expressions such as variables. We next evaluate our condition
, if true, the loop statements will execute. If false, the loop terminates.
Then the statement
executes. When we wish to execute multiple statements, we use a block statement ({ ... }
) to group the together. If present, the update expression incrementExpression
is executed. Control then returns to evaluating the condition
.
Let’s now return to our previous example:
let i;
for (i = 0; i < 10; i++) {
document.write("Take one…