DEV Community

Cover image for The Common Loops In JavaScript
Sapinder Singh
Sapinder Singh

Posted on • Originally published at blog.sapinder.dev

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!

What'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 are 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 see what these are, and when to use each of them.

The Different Kinds of Loops

do...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 (...)
Enter fullscreen mode Exit fullscreen mode

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-

1. let index = 1;
2. 
3. do {
4.   console.log('Hello!');
5.   index = index + 1;
6. } while(index <= 5)
Enter fullscreen mode Exit fullscreen mode

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.

The increment operator) (++) is a shorthand operator that allows us to write index++ instead of index = index + 1. There's also a decrement operator (--) as its counterpart. Look them up! πŸ‘

while

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 (...) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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-

1. let name = 'Sapinder';
2. 
3. {
4.   let name = 'Singh';
5.   console.log(name);
6. }
7. 
8. console.log(name);
Enter fullscreen mode Exit fullscreen mode

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.

for

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!');
}
Enter fullscreen mode Exit fullscreen mode

Yes! It's just the same as the following while loop-

let index = 1;

while (index <= 5) {
  console.log('Hello!');
  index++;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

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're 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 this post, and want me to create more content like this, please do subscribe to my newsletter, and follow me here, or on my twitter handle!

Peace! 🀞

Discussion (2)

Collapse
jonrandy profile image
Jon Randy • Edited on

I quite like this syntax...

for (i of 1[ to(10) ]) {
  console.log(i)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
sapinder_dev profile image
Sapinder Singh Author

It’s all comes down to personal preference πŸ™‚