JavaScript Loops

Loops in JavaScript provide a way for us to run a piece of code repeatedly over and over until a certain condition is met. Without loops, it becomes very time consuming and tiresome to type the same code over and over manually.

For a computer, loops are extremely important. As a programmer or a software engineer, we are taught the term “DRY“. It means “Don’t Repeat Yourself“.

So, it is only fair that we should not write code that we want to run repeatedly, in a manual way. Thus, loops are introduced.


Why we need loops? 🤔

Some of the reasons why we need loops are given below:

  • To write a piece of code once, and run it over and over again with different values.
  • To check a variable or a constant until it has reached a certain value or fulfilled a certain condition.
  • To follow the “DRY” principle (“Don’t Repeat Yourself“).
  • To provide a readable and short code format.
  • To provide a better way to write algorithms.

Example without loop


const fruits = ['Apple', 'Mango', 'Banana', 'Strawberry', 'Guava', 'Grapes'];

// Without loops, just to display each array element, we had to write "console.log" six times
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[3]);
console.log(fruits[4]);
console.log(fruits[5]);

Output

Apple
Mango
Banana
Strawberry
Guava
Grapes

Example with loop


const fruits = ['Apple', 'Mango', 'Banana', 'Strawberry', 'Guava', 'Grapes'];

// Using a loop, we can display each array element using a shorter code format.
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

Output

Apple
Mango
Banana
Strawberry
Guava
Grapes

NOTE: Don’t worry about the code that we used just now. It’s called a for Loop and you’ll learn about it in our next lesson.


Types of Loops in JavaScript loops 🔄

The following are the available types of loops in JavaScript:


In our further lessons, we will learn about every single one of the loops given above.