DEV Community

ABISHEK M
ABISHEK M

Posted on

🔄 Loops in JavaScript

Imagine a teacher wants to greet 5 students:

Hello Arun
Hello Kumar
Hello Ravi
Hello Priya
Hello Divya
Enter fullscreen mode Exit fullscreen mode

Without a loop, we need to write the same code multiple times.

console.log("Hello Arun");
console.log("Hello Kumar");
console.log("Hello Ravi");
console.log("Hello Priya");
console.log("Hello Divya");
Enter fullscreen mode Exit fullscreen mode

Instead of writing the same type of code again and again, JavaScript provides loops.


🔄 What is a Loop?

  • A loop is used to execute a block of code repeatedly.
  • It helps us avoid writing the same code again and again.
  • A loop continues running based on a condition or a collection of values.

In simple words:

A loop means repeating a task multiple times using code.

For example:

For every student:
    Print the student's name
Enter fullscreen mode Exit fullscreen mode

This is the basic idea of a loop.


🤔 Why Do We Use Loops?

Loops are useful when the same task needs to be performed multiple times.

For example, without a loop:

console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
Enter fullscreen mode Exit fullscreen mode

Using a loop:

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

Output:

Hello
Hello
Hello
Hello
Hello
Enter fullscreen mode Exit fullscreen mode

If the task needs to be performed 100 or 1000 times, using a loop is much easier than writing the same code repeatedly.


📍 Where Are Loops Used?

Loops can be used in many situations, such as:

  • Displaying a list of products
  • Processing a list of students
  • Reading values from an array
  • Printing numbers
  • Calculating marks
  • Processing multiple records
  • Repeating a task until a condition becomes false

For example:

For every product:
    Display the product
Enter fullscreen mode Exit fullscreen mode

⏰ When Should We Use a Loop?

A loop can be used when:

The same task needs to be performed multiple times.

For example:

For every student:
    Display the student's name
Enter fullscreen mode Exit fullscreen mode

or:

While the password is incorrect:
    Ask for the password again
Enter fullscreen mode Exit fullscreen mode

Different situations require different types of loops.


🔢 Types of Loops in JavaScript

JavaScript provides different types of loops:

  1. for loop
  2. while loop
  3. do...while loop
  4. for...of loop
  5. for...in loop

Let's look at each loop one by one.


1. 🔁 for Loop

  • The for loop is used to execute a block of code repeatedly.
  • It is commonly used when the number of repetitions is known or can be controlled.
  • A for loop has three main parts: initialization, condition, and update.

🌍 Real-World Example

Imagine a teacher says:

"Write your name 5 times."

The task can be represented as:

1 → Write name
2 → Write name
3 → Write name
4 → Write name
5 → Write name
→ Stop
Enter fullscreen mode Exit fullscreen mode

A for loop can be used for this type of task.

Syntax

for (initialization; condition; update) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Three Parts of a for Loop

1. Initialization

Defines where the loop starts.

let i = 1;
Enter fullscreen mode Exit fullscreen mode

2. Condition

Checks whether the loop should continue.

i <= 5
Enter fullscreen mode Exit fullscreen mode

If the condition is true, the code executes.

If the condition is false, the loop stops.

3. Update

Changes the value after each iteration.

i++;
Enter fullscreen mode Exit fullscreen mode

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

How Does It Work?

i = 1
 ↓
Check condition
 ↓
1 <= 5 → true
 ↓
Print 1
 ↓
i++
 ↓
i = 2
 ↓
Check condition
 ↓
2 <= 5 → true
 ↓
Print 2
 ↓
...
 ↓
6 <= 5 → false
 ↓
Stop
Enter fullscreen mode Exit fullscreen mode

When to Use for Loop?

Use a for loop when the number of repetitions is known or can be controlled.


2. 🔄 while Loop

  • The while loop executes a block of code as long as a condition is true.
  • The condition is checked before executing the code.
  • If the condition is false at the beginning, the code inside the loop will not execute.

🌍 Real-World Example

Imagine charging a mobile phone.

The idea can be:

While battery < 100%:
    Keep charging
Enter fullscreen mode Exit fullscreen mode

The charging continues while the condition is true.

Syntax

while (condition) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Example

let i = 1;

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

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

The execution looks like this:

Check condition
      ↓
Is it true?
   ↙       ↘
 Yes        No
  ↓          ↓
Execute     Stop
  ↓
Update
  ↓
Check again
Enter fullscreen mode Exit fullscreen mode

⚠️ Infinite Loop

An infinite loop is a loop that never stops because its condition always remains true.

For example:

let i = 1;

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

Here, i is never changed.

So the condition always remains:

1 <= 5 → true
Enter fullscreen mode Exit fullscreen mode

The loop keeps running continuously.

❌ How to Avoid an Infinite Loop?

Make sure the value used in the condition is updated so that the condition can eventually become false.

let i = 1;

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

Here:

i++;
Enter fullscreen mode Exit fullscreen mode

changes the value:

1 → 2 → 3 → 4 → 5 → 6
Enter fullscreen mode Exit fullscreen mode

When i becomes 6:

6 <= 5 → false
Enter fullscreen mode Exit fullscreen mode

So the loop stops.

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

To avoid an infinite loop, make sure the loop condition can eventually become false.

When to Use while Loop?

Use a while loop when the repetition mainly depends on a condition.


3. 🔁 do...while Loop

  • The do...while loop is similar to the while loop.
  • The main difference is that the code executes before the condition is checked.
  • Because of this, the code inside the loop executes at least once.

🌍 Real-World Example

Imagine an ATM asking for a PIN.

The user needs to enter the PIN at least once.

The process can be represented as:

DO:
    Enter PIN

WHILE:
    PIN is incorrect
Enter fullscreen mode Exit fullscreen mode

Syntax

do {
    // code to execute
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Example

let i = 1;

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

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

How Does It Work?

Execute code
     ↓
Check condition
     ↓
Is it true?
  ↙       ↘
Yes       No
 ↓         ↓
Repeat    Stop
Enter fullscreen mode Exit fullscreen mode

while vs do...while

while
→ Check condition first
→ Execute if true

do...while
→ Execute first
→ Check condition later
Enter fullscreen mode Exit fullscreen mode

For example:

let i = 10;

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

Nothing is printed because the condition is checked first:

10 <= 5 → false
Enter fullscreen mode Exit fullscreen mode

But:

let i = 10;

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

prints:

10
Enter fullscreen mode Exit fullscreen mode

because the code executes once before checking the condition.

When to Use do...while?

Use do...while when the code needs to execute at least once.


4. 🔄 for...of Loop

  • The for...of loop is used to iterate over the values of an iterable.
  • It is commonly used with arrays and strings.
  • It takes one value at a time.

In simple words:

for...of takes values one by one.

🌍 Real-World Example

Imagine a bag containing:

Apple
Banana
Orange
Mango
Enter fullscreen mode Exit fullscreen mode

Taking the fruits one by one is similar to how for...of works.

Syntax

for (const value of iterable) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Example

const fruits = ["Apple", "Banana", "Orange"];

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

Output:

Apple
Banana
Orange
Enter fullscreen mode Exit fullscreen mode

Here, fruit gets each value one by one:

Apple
↓
Banana
↓
Orange
Enter fullscreen mode Exit fullscreen mode

for...of With a String

const name = "Abishek";

for (const character of name) {
    console.log(character);
}
Enter fullscreen mode Exit fullscreen mode

Output:

A
b
i
s
h
e
k
Enter fullscreen mode Exit fullscreen mode

When to Use for...of?

Use for...of when you need to work with the values of an array, string, or another iterable.

Remember:

for...of → Values
Enter fullscreen mode Exit fullscreen mode

5. 🔄 for...in Loop

  • The for...in loop is mainly used to iterate over the keys (property names) of an object.
  • It takes one key at a time.
  • The key can be used to access its corresponding value.

In simple words:

for...in takes object keys one by one.

🌍 Real-World Example

Imagine a person's information:

Name → Abishek
Age  → 21
City → Chennai
Enter fullscreen mode Exit fullscreen mode

Here:

Name → Key
Age  → Key
City → Key
Enter fullscreen mode Exit fullscreen mode

And:

Abishek → Value
21      → Value
Chennai → Value
Enter fullscreen mode Exit fullscreen mode

Syntax

for (const key in object) {
    // code to execute
}
Enter fullscreen mode Exit fullscreen mode

Example

const person = {
    name: "Abishek",
    age: 21,
    city: "Chennai"
};

for (const key in person) {
    console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

Output:

name
age
city
Enter fullscreen mode Exit fullscreen mode

Here, key gets each property name.

Getting Both Key and Value

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

Output:

name Abishek
age 21
city Chennai
Enter fullscreen mode Exit fullscreen mode

When to Use for...in?

Use for...in mainly when you need to work with the keys of an object.

Remember:

for...in → Keys
Enter fullscreen mode Exit fullscreen mode

🔥 for...in vs for...of

These two loops can be confusing because their names are similar.

The easiest way to remember them is:

for...in → Keys
for...of → Values
Enter fullscreen mode Exit fullscreen mode

for...in

const person = {
    name: "Abishek",
    age: 21
};

for (const key in person) {
    console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

Output:

name
age
Enter fullscreen mode Exit fullscreen mode

for...of

const fruits = ["Apple", "Banana"];

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

Output:

Apple
Banana
Enter fullscreen mode Exit fullscreen mode

🤔 Which Loop Should You Use?

Requirement Loop
Repeat a specific number of times for
Repeat while a condition is true while
Execute at least once do...while
Get values from an array/string for...of
Get keys from an object for...in

📌 NOTE:

Loops are used to repeat code without writing the same code again and again.

The commonly used JavaScript loops are:

for
while
do...while
for...of
for...in
Enter fullscreen mode Exit fullscreen mode

A simple way to remember them:

for
→ Repeat a specific number of times

while
→ Repeat while condition is true

do...while
→ Execute first, then check

for...of
→ Values

for...in
→ Keys
Enter fullscreen mode Exit fullscreen mode

Choose the loop based on what needs to be repeated and how the repetition should be controlled.

Top comments (0)