DEV Community

Cover image for JavaScript: Look! Loops!
Dwaipayan C(Dtech-Dbug)
Dwaipayan C(Dtech-Dbug)

Posted on

JavaScript: Look! Loops!

Now that we have covered control flows and have a little bit of idea about conditionals, its time we move to one of the most important concepts of programming - loops.

What is s Loop?

A loop is set of inctructions that are executed until a certain condition is met.

How about a practical example? Just to reassure - it's most definitely not rocket science.

Imagine, you have 4 identical boxes. One of the boxes have insert your incentive what you are looking for. How would you find that?

You would, most probably,search each of the boxes until you find just what you are looking for, right?

In the programming paradigm, you are just essentially looping through the boxes until you find what you are looking for.

Now, lets write a pseudo code for that? Shall we?

(loop through each of the 4 boxes)
if(the box has what you are looking for){
 break the loops;
}
else{
keep on searching, until you find what you are looking for
}
Enter fullscreen mode Exit fullscreen mode

That was easy.

But wait. Hold On. There's a catch.
Since all the boxes are identical, you have to make sure to somehow differentiate or mark the boxes that are already searched, without that - you could potentially end up searching the 4 boxes forever, unless ofcourse you exit/break out of it. Come to think of it?

What are the different kinds of loops used in programming?

The two most widely used loops are - for-loops and while-loops.

Let's discuss in short about both of them to gain a better understanding of each.

For-Loops

A for loop is a type of loop in programming that is used to execute a set of statements repeatedly for a fixed number of times.

Typically, they involve:

  • a loop variable -> to keep track of the index of loop. Remember the 'marking' part in the practical example?

  • a condition -> this determines on what condition will the loop stop, or in other words how long shall the loop run. In the practical example of box-searching - 'find what you are looking' was the condition. Until that was met you had to keep searching the boxes. Making sense?

  • a step -> this increments the loop variable, after an iteration is completed to start the next iteration.

A general for loop syntax will look like this:

for (initialise loop variable; define condition; step)
{
// code block
// what to do
}
Enter fullscreen mode Exit fullscreen mode

The control flows in this order:

  1. The condition is checked, if its true the control enters the code block, if it's false the control exits the loop.
  2. After the control is inside the code block the block is executed and the loop variable is stepped.
  3. Back to step 1.

Challenge!
Guess the output of the below snippet.

for(let i=0; i < 10; i++)
{
console.log(i)
}
// guess the output?
Enter fullscreen mode Exit fullscreen mode

While-Loops

A while loop is a type of loop in programming that repeatedly executes a block of code as long as a specified condition is true.

The principles of the while-loop is pretty similar to for-loops,but the semantics are quiete different.

For example a typical, while loop syntax will look like:

// loop variable init
let i = 0;

while(condition){
 // code block

 // step up or step down the loop variable
// in this case, since the loop var is initialised with 0, we will increment it by 1
i++;
}
Enter fullscreen mode Exit fullscreen mode

Note: while implementing while loops, we have to be extra cautious about stepping up or stepping down the variable otherwise we might run into an infinite loop.

Consider the following example:

while(true){
 console.log('RUNNING INIFINITE WHILE LOOP)
}
// this code doesnt know when to stop, therefore it wont.
// this can cause problems like memory leaks
Enter fullscreen mode Exit fullscreen mode

When to use for and while loops?

Anything that can be achieved with for loops can be achieved with while loops.

However, they have their own specific use cases.

For-Loops are the best when you know eaxctly how many times you want to execute the set of instructions.

While-Loops, when you dont know how long should a loop run, but you only know the condition on which the loop can exit.

Some important concepts/keywords of loops:

  • break : the break keyword can be used to exit a loop prematurely when a certain condition is met, saving the time to iterate any further.

  • continue : the continue keyword can be used to skip the current iteration and go to the next value.

To put things into perspective using the box-searching pseudo-code example:


// considering there are 4 boxes, and one of them has your thing of interest in it

// note here i = represents the current box

for(let i = 0; i < 4; i++)
{
 if(i doesn't have the thing of interest in it){
  continue;
}
else{
  break;
}
}
Enter fullscreen mode Exit fullscreen mode

Note: you can initialize the loop variable with 1, but a more widely adopted approach is initializing it with 0.
Interested to learn more? Read about 0-based indexing.

It's a Wrap!

  • Loops are one of the most fundamental tools for problem solving.
  • The most common types of loops are for-loops and while-loops.
  • While both of them can be used interchangeably, they do have their own use case.
  • For-loops are more generally used when the numbers of times the loop has to run is known or fixed.
  • While-loops are more generally used when the number of times the loop should run is unknown and only the condition on which the loop exits is known.
  • While-loops are particularly tricky, if not written properly as they might lead to problems like inifinite loops which in turn results to memory leaks and buggy code.

With that, we have a slightly better idea about loops and how to use them in context.

Variations of For-loops in JS

This part is only if you are willing to explore a little more. No harm if you skip this section.

JavaScript has a couple of variations of for loops introduced in ECMAScript 2015:

Top comments (0)