The Common Loops In JavaScript
Looping is one of my favourite programming concepts that I learned as a beginner. It's simple; yet an effective way to avoid code repetition. If you are struggling to grasp the various kinds of loops that we see in JavaScript, this article is made for you indeed. 😉 Also, I've tried to keep it as general as possible so that anyone could understand even if they don't know JavaScript. So, let's jump right into it!
Link to this headingWhat's the need for loops?
Loops help us avoid code repetition. In other words, they allow us to execute the same set of instructions for a specified number of times. Usually, we have to deal with large sets of data for which, we have to perform same tasks over and over again. Loops are made for this job because we can just avoid typing the same statements again and again with our lazy hands 🥱. But there're many kinds of loops in JavaScript; how would you know which one to use in what case? I'm going to discuss the three common loops in this post- do...while, while and for. So, let's what these are, and when to use each of them.
Link to this headingThe Different Kinds of Loops
Link to this headingdo...while
I chose this loop to be discussed first because it seems closer to the way I want you to start thinking about loops. Its syntax is simple enough to comprehend-
do {
...
} while (...)
The instructions to be performed go inside curly braces {}
after the do
keyword, whereas, parentheses ()
hold the condition that
will be checked before repeating those instructions each time. Unless if we were talking to a human, we can't just say "Print 'hello' 5 times"
.
The way loops work is that they check some condition before repeating the task each time. If the condition evaluates to true
, the
task is performed again; otherwise it exits the loop. Consider this example that prints Hello!
5 times to the console/terminal-
let index = 1;
do {
console.log('Hello!');
index = index + 1;
} while(index <= 5)
Notice the use of index
variable in the snippet above. Firstly, we declare this variable and assign the integer value 1
to it. Then
we tell the computer to run the statements inside do{}
block; then evaluate the condition index <= 5
; and run those statements
again if it's true; or exit the loop if not.
If we forget to include the line number 5 in our code, the loop will become infinite because the value of index
will always be 1; hence
the condition will be true forever. Therefore, it is necessary to increment the value each time the loop is run. When the value of index
equals 5, the condition will turn to false; hence, it will exit the loop.
Link to this headingwhile
The while
loop is exactly the same as do...while
. Just have a look at the syntax of both loops-
// do...while loop
do {
...
} while (...)
// while loop
while (...) {
...
}
Can you spot the difference? The do...while
loop runs the statement first, then checks for the condition; whereas while
loop checks
the condition first, then runs the statement. In short, the former checks condition for the next iteration, while the latter checks
condition for the current iteration.
The answer to the question "Which of these loops should we use?" is quite opinionated. I personally don't remember the time that I used
do...while
loop, except while I was learning it. while
loop is used much often in such cases. But there's another type of loop that
is the most common among all others- the for
loop.
Before introducing for
loop, I want you to understand the concept of scope in
programming. The scope of a variable can be defined as the range of statements in which that variable can be accessed. Consider
the following snippet for example-
let name = 'Sapinder';
{
let name = 'Singh';
console.log(name);
}
console.log(name);
What do you think line number 5 and 8 would print to the console? The first console.log
statement will print Singh
but the
second one will print Sapinder
because the scope of variable holding the value Singh
is limited to the inner block. It can't be
accessed out of the those curly braces. Hence, when the compiler reaches line number 8, it only knows of the variable name
that holds
the value Sapinder
. Also, notice that I used let
keyword instead var
because a variable declared with var
is always globally scoped
regardless of where it is declared. Now that you know what scoping is, let's learn about the for
loop.
Link to this headingfor
I like to think of the for
loop as a more concise version of while
loop. Both of these are almost the same except for a few things that
we'll see later. First, take a look at an example of for
loop-
for(let index = 1; index <= 5; index++) {
console.log('Hello!');
}
Yes! It's just the same as the following while
loop-
let index = 1;
while (index <= 5) {
console.log('Hello!');
index++;
}
The initialization of variable, the condition and the upgrading of value, all of these things can be achieved in single line of code in a
for
loop. Moreover, the variable index
is initialized as block-scoped, unlike as in the example of while
loop. This is major
benefit of using a for
loop because it avoids any chance of conflicting names at the global level. To understand another difference
between both the loops, I would like to introduce two keywords-
- break - The keyword
break
is used to terminate/exit a loop. The compiler will terminate the loop as soon as this keyword is encountered. - continue - The keyword
continue
is used to skip the rest of statements left in the current iteration, and start the next iteration in the loop.
Now, consider the following example where I want to print the numbers from 1 to 5 excluding the number 3-
for(let index = 1; index <= 5; index++) {
if(index === 3) {
continue;
}
console.log(index);
}
Here, I'm saying, "If index is equal to 3, don't run rest of the statements; and just skip to the next iteration." Hence, it will not
print the number 3
to the console. It will continue the loop with upgraded value of index
, i.e. 4
. Now, let's go for the same
approach using while
loop-
let index = 1;
while(index <= 5) {
if(index === 3) {
continue;
}
console.log(index);
index++; // upgrading needs to be done here in the end, unlike in `for` loop
}
Do you think this solution will work out? Can you spot the bug? Well, it is an infinite loop because once the value of index
reaches
3
, it skips the rest of the statements including index++
. Hence, its value is never upgraded beyond 3
; and the loop keeps running
infinitely.
Such a case can easily be handled using a for
loop because the upgrading expression of the loop is specified at the very beginning; and
it is always executed at the end of each iteration. But if we move this upgrading expression from the first line of loop to just before
the end of loop, as in the following example, we will again get the infinite loop problem.
for(let index = 1; index <=5;) {
if(index === 3) {
continue;
}
console.log(index);
/* This will cause the same issue of infinite loop */
index++;
}
So, to conclude, I would say that both the for
and while
loops can be used interchangeably except for some cases, where we're more
likely to cause bugs using while
loop, as compared to the other one. There are other kinds of loops too in JavaScript, such as- for in
, for of
, etc.,
but they are literally dead simpler than the ones discussed above; and don't need to be included in this post.
If you like my writing style, then you can join my mailing list so that you never miss any of my future posts! Also, please mind pressing the Like button to let me know that you enjoyed this post!
Peace! 🤞