DEV Community

Lokesh
Lokesh

Posted on

Loops in JavaScript

What Are Loops?

Loops are used to execute a block of code repeatedly until a condition is no longer satisfied or the loop is otherwise stopped.

For example, if we want to print numbers from 1 to 10, we don't need to write ten separate console.log() statements. We can use a loop instead.

JavaScript provides different types of loops. Let's understand the most common ones.

1. for Loop

A for loop is useful when we know how many times we want to repeat something.

Example:

for (let i = 1; i <= 5; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Let's understand the three parts:

  • let i = 1 — starts the counter at 1.
  • i <= 5 — continues the loop while the condition is true.
  • i++ — increases the counter by 1 after each iteration.

The loop stops when i becomes 6 because the condition is no longer true.

2. while Loop

A while loop repeats as long as its condition is true.

Example:

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

This also prints numbers from 1 to 5.

The difference is that we declare the counter before the loop and update it inside the loop.

Remember to update the counter when necessary. Otherwise, the loop might run forever.

3. do...while Loop

A do...while loop executes the code block at least once before checking the condition.

Example:

let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);
Enter fullscreen mode Exit fullscreen mode

This prints numbers from 1 to 5.

Even if the condition is false at the beginning, the code inside do executes once.

4. for...of Loop

A for...of loop is used to access the values of an iterable, such as an array or string.

Example:

let fruits = ["Apple", "Banana", "Mango"];

for (let fruit of fruits) {
    console.log(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Apple
Banana
Mango
Enter fullscreen mode Exit fullscreen mode

This loop is useful when we want to process each item in an array.

5. for...in Loop

A for...in loop is commonly used to iterate over the enumerable property keys of an object.

Example:

let student = {
    name: "John",
    age: 22,
    course: "CSE"
};

for (let key in student) {
    console.log(key, student[key]);
}
Enter fullscreen mode Exit fullscreen mode

Output:

name John
age 22
course CSE
Enter fullscreen mode Exit fullscreen mode

Here, key represents a property name, and student[key] accesses its value.

For arrays, for...of is generally a better choice when you want to access each value.

Why Are Loops Important?

Loops help us:

  • Print numbers and patterns.
  • Process arrays of products or student records.
  • Repeat calculations.
  • Perform the same task without writing the same code multiple times.

Top comments (0)