Imagine a teacher wants to greet 5 students:
Hello Arun
Hello Kumar
Hello Ravi
Hello Priya
Hello Divya
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");
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
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");
Using a loop:
for (let i = 1; i <= 5; i++) {
console.log("Hello");
}
Output:
Hello
Hello
Hello
Hello
Hello
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
⏰ 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
or:
While the password is incorrect:
Ask for the password again
Different situations require different types of loops.
🔢 Types of Loops in JavaScript
JavaScript provides different types of loops:
-
forloop -
whileloop -
do...whileloop -
for...ofloop -
for...inloop
Let's look at each loop one by one.
1. 🔁 for Loop
- The
forloop 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
forloop 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
A for loop can be used for this type of task.
Syntax
for (initialization; condition; update) {
// code to execute
}
Three Parts of a for Loop
1. Initialization
Defines where the loop starts.
let i = 1;
2. Condition
Checks whether the loop should continue.
i <= 5
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++;
Example
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
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
When to Use for Loop?
Use a for loop when the number of repetitions is known or can be controlled.
2. 🔄 while Loop
- The
whileloop executes a block of code as long as a condition istrue. - The condition is checked before executing the code.
- If the condition is
falseat 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
The charging continues while the condition is true.
Syntax
while (condition) {
// code to execute
}
Example
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1
2
3
4
5
The execution looks like this:
Check condition
↓
Is it true?
↙ ↘
Yes No
↓ ↓
Execute Stop
↓
Update
↓
Check again
⚠️ 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);
}
Here, i is never changed.
So the condition always remains:
1 <= 5 → true
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++;
}
Here:
i++;
changes the value:
1 → 2 → 3 → 4 → 5 → 6
When i becomes 6:
6 <= 5 → false
So the loop stops.
Output:
1
2
3
4
5
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...whileloop is similar to thewhileloop. - 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
Syntax
do {
// code to execute
} while (condition);
Example
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Output:
1
2
3
4
5
How Does It Work?
Execute code
↓
Check condition
↓
Is it true?
↙ ↘
Yes No
↓ ↓
Repeat Stop
while vs do...while
while
→ Check condition first
→ Execute if true
do...while
→ Execute first
→ Check condition later
For example:
let i = 10;
while (i <= 5) {
console.log(i);
}
Nothing is printed because the condition is checked first:
10 <= 5 → false
But:
let i = 10;
do {
console.log(i);
} while (i <= 5);
prints:
10
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...ofloop 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...oftakes values one by one.
🌍 Real-World Example
Imagine a bag containing:
Apple
Banana
Orange
Mango
Taking the fruits one by one is similar to how for...of works.
Syntax
for (const value of iterable) {
// code to execute
}
Example
const fruits = ["Apple", "Banana", "Orange"];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
Orange
Here, fruit gets each value one by one:
Apple
↓
Banana
↓
Orange
for...of With a String
const name = "Abishek";
for (const character of name) {
console.log(character);
}
Output:
A
b
i
s
h
e
k
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
5. 🔄 for...in Loop
- The
for...inloop 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...intakes object keys one by one.
🌍 Real-World Example
Imagine a person's information:
Name → Abishek
Age → 21
City → Chennai
Here:
Name → Key
Age → Key
City → Key
And:
Abishek → Value
21 → Value
Chennai → Value
Syntax
for (const key in object) {
// code to execute
}
Example
const person = {
name: "Abishek",
age: 21,
city: "Chennai"
};
for (const key in person) {
console.log(key);
}
Output:
name
age
city
Here, key gets each property name.
Getting Both Key and Value
for (const key in person) {
console.log(key, person[key]);
}
Output:
name Abishek
age 21
city Chennai
When to Use for...in?
Use for...in mainly when you need to work with the keys of an object.
Remember:
for...in → Keys
🔥 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
for...in
const person = {
name: "Abishek",
age: 21
};
for (const key in person) {
console.log(key);
}
Output:
name
age
for...of
const fruits = ["Apple", "Banana"];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
🤔 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
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
Choose the loop based on what needs to be repeated and how the repetition should be controlled.
Top comments (0)