JavaScript Loops and Iteration
Learn how to execute a block of code repeatedly using JavaScript loops. Understand for, while, do-while, for...of, for...in, break, and continue with detailed examples and expected outputs.
1. What Are Loops in JavaScript?
A loop is a programming structure that executes a block of code repeatedly while a condition is satisfied or while items remain to be processed.
For example, if we want to display numbers from 1 to 100, we do
not need to write 100 separate console.log() statements.
A loop can perform the same task using a few lines of code.
JavaScript provides several types of loops:
forloopwhileloopdo...whileloopfor...ofloopfor...inloop
2. How Does a Loop Work?
A typical loop initializes a variable, checks a condition, executes the loop body, updates the variable, and checks the condition again.
Start
Initialize Variable
let i = 1
Check Condition
i <= 5
True
Execute loop body and update variable
False
Exit the loop
When the condition is true, execution returns to the condition check after the loop body and update.
3. The for Loop
A for loop is useful when the number of iterations
is known or when a variable controls how many times the code runs.
Syntax
for (initialization; condition; update) {
// Code to execute repeatedly
}
The three parts of a standard for loop are:
- Initialization: Sets the starting value.
- Condition: Determines whether the next iteration runs.
- Update: Changes the loop variable after each iteration.
Example: Print Numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output
1
2
3
4
5
Explanation:
The variable i starts at 1. The loop continues
while i <= 5. After every iteration,
i++ increases the value by one.
4. The while Loop
A while loop checks its condition before executing
the loop body. If the condition is false at the beginning,
the body does not execute.
Syntax
while (condition) {
// Code to execute
}
Example: Print Even Numbers
let number = 2;
while (number <= 10) {
console.log(number);
number += 2;
}
Output
2
4
6
8
10
Explanation: The loop starts with 2 and increases the number by 2 after each iteration. When the number becomes 12, the condition becomes false and the loop stops.
5. The do...while Loop
A do...while loop executes the loop body first and
checks the condition afterward. Therefore, the body executes at
least once, even if the condition is initially false.
Syntax
do {
// Code to execute
} while (condition);
Example
let i = 1;
do {
console.log(i);
i++;
} while (i <= 3);
Output
1
2
3
Important Difference
let number = 10;
do {
console.log("Executed once");
} while (number < 5);
Output
Executed once
The condition is false, but the message is still displayed once
because a do...while loop checks its condition after
executing the body.
6. Difference Between for, while and do...while
| Feature | for | while | do...while |
|---|---|---|---|
| Condition checked | Before each iteration | Before each iteration | After each iteration |
| Minimum executions | Zero | Zero | One |
| Typical use | Counter-controlled repetition | Repeat while a condition is true | Execute once before checking |
7. The for...of Loop
The for...of loop iterates over the values of an
iterable, such as an array or string. It is particularly useful
when we want to process each item in a collection.
Example: Display Course Names
let courses = ["JavaScript", "Node.js", "React"];
for (let course of courses) {
console.log(course);
}
Output
JavaScript
Node.js
React
Explanation:
In each iteration, the variable course receives
the next value from the array.
8. The for...in Loop
The for...in loop iterates over enumerable property
keys of an object. It is useful when you need to inspect an
object's property names.
Example: Display Student Details
let student = {
name: "Samadhan",
age: 22,
course: "JavaScript"
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
Output
name: Samadhan
age: 22
course: JavaScript
Explanation:
The variable key receives each property name.
The expression student[key] accesses the value
associated with that property.
for...of for iterating over array values.
A for...in loop iterates over property keys and
may also include inherited enumerable properties.
9. Choosing the Right Loop
Different loops are useful for different requirements. This diagram summarizes when to consider each loop type.
What Do You Need to Repeat?
Known Counter
Use for
Condition-Based Repetition
Use while
Run Body at Least Once
Use do...while
Collection Values
Use for...of
Object Property Keys
Use for...in
10. The break Statement
The break statement immediately terminates the
nearest enclosing loop. Program execution then continues after
that loop.
Example
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
Output
1
2
3
4
When i becomes 5, the condition is true and
break terminates the loop. The number 5 is not printed.
11. The continue Statement
The continue statement skips the remaining statements
in the current iteration and proceeds to the next iteration.
Example: Skip Number 3
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
Output
1
2
4
5
When i equals 3, the current iteration is skipped.
The loop continues with the next value, 4.
12. Practical Program: Calculate Total Marks
Let us use a loop to calculate the total marks obtained by a student in three subjects.
Step 1: Create a File
Create a file named totalmarks.js.
Step 2: Write the Program
let marks = [80, 75, 90];
let total = 0;
for (let i = 0; i < marks.length; i++) {
total += marks[i];
}
let average = total / marks.length;
console.log("Total Marks:", total);
console.log("Average Marks:", average);
Step 3: Run the Program
node totalmarks.js
Step 4: Expected Output
Total Marks: 245
Average Marks: 81.66666666666667
Explanation:
The loop visits each element of the marks array and adds it to
total. The program then divides the total by the
number of subjects to calculate the average.
13. Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Infinite loop | The condition never becomes false. | Check the condition and update the loop variable correctly. |
| Off-by-one error | The loop executes one time too many or too few. | Check the starting value and boundary condition. |
| Forgetting to update | A while loop may never reach its exit condition. | Update the variable when required. |
| Using for...in for array values | It iterates over property keys, not directly over values. | Use for...of when processing array values. |
| Confusing break and continue | Break exits the loop; continue skips an iteration. | Use the statement that matches the requirement. |
14. Practice Task
Number and Marks Processing
Create a JavaScript program that performs the following tasks:
- Use a
forloop to print numbers from 1 to 10. - Use a
whileloop to print even numbers from 2 to 20. - Use a
do...whileloop to display a message at least once. - Use
for...ofto display an array of course names. - Use
for...into display the properties of a student object. - Use
breakto stop a loop at a specified number. - Use
continueto skip a particular number. - Calculate the total and average of an array of marks.
Important Points
- Use
forwhen a counter controls repetition. - Use
whilewhen repetition depends on a condition. - A
do...whileloop executes at least once. - Use
for...ofto iterate over iterable values. - Use
for...into iterate over enumerable object property keys. breakterminates the nearest enclosing loop.continueskips the current iteration and proceeds to the next one.
Summary
JavaScript loops allow us to execute code repeatedly without writing the same statements multiple times. The for, while, and do...while loops support different repetition patterns. The for...of loop processes iterable values, while for...in iterates over enumerable property keys. The break and continue statements provide additional control over loop execution. These concepts are useful for processing arrays, calculating totals, validating data, and automating repetitive tasks.