Choose a Loop
Choose a Loop
A loop repeats instructions. for suits a count, while suits a changing condition, and for...of visits array values. A school report should choose the traversal that matches its data rather than copying a loop mechanically.
Before this topic, review Choose a Result with Conditions if its terms are unfamiliar.
What you’ll learn
- Explain choose a loop through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The traversal reads each value from the edited collection.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const marks = [70, 80];
for (const mark of marks) console.log(mark);
Expected output
70
80Run in JavaScript compiler →Understanding Loops in JavaScript
In programming, we often need to repeat a set of instructions until a condition is met. Loops help us do just that — efficiently and elegantly. JavaScript provides several types of loops, each suitable for specific use cases.
Why Use Loops?
Imagine printing a message 100 times or processing each item in a list. Writing repetitive lines of code would be inefficient and error-prone. Loops let you:
- Run the same code multiple times
- Iterate over arrays or objects
- Automate tasks in your logic flow
The for Loop
The most common loop in JavaScript. Ideal when you know how many times to repeat the code.
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
How it Works
i = 1 is the initializer. i <= 5 is the condition. If true, the loop runs. After each iteration, i++ increments i by 1. The loop stops when the condition is false.
The while Loop
Used when you don't know how many times to repeat — the condition is checked before the loop body runs.
let count = 1;
while (count <= 3) {
console.log("While Loop Run:", count);
count++;
}
While Loop Run: 1
While Loop Run: 2
While Loop Run: 3
The do...while Loop
This loop guarantees at least one execution, as the condition is checked after the loop body.
let x = 5;
do {
console.log("Do-While Value:", x);
x--;
} while (x > 3);
Do-While Value: 5
Do-While Value: 4
The for...of Loop
Perfect for looping over array values or iterable objects.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log("Color:", color);
}
Color: red
Color: green
Color: blue
The for...in Loop
Used to iterate over the enumerable properties of an object (like keys).
const user = { name: "Alex", age: 30, city: "Berlin" };
for (const key in user) {
console.log(key + ":", user[key]);
}
name: Alex
age: 30
city: Berlin
Loop Control Statements
Break
Exits the loop immediately.
for (let i = 0; i < 10; i++) {
if (i === 4) break;
console.log("Break Example:", i);
}
Break Example: 0
Break Example: 1
Break Example: 2
Break Example: 3
Continue
Skips to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log("Continue Example:", i);
}
Continue Example: 1
Continue Example: 2
Continue Example: 4
Continue Example: 5
Nested Loops
Loops inside loops are useful for multi-dimensional arrays or grid-like structures.
for (let i = 1; i <= 2; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
Real-World Example: Summing Numbers in an Array
const nums = [10, 20, 30, 40];
let sum = 0;
for (let num of nums) {
sum += num;
}
console.log("Total Sum:", sum);
Total Sum: 100
When to Use Which Loop?
for– when the number of iterations is known.while– when the condition controls the flow.do...while– when you must run the loop at least once.for...of– for arrays and iterables.for...in– for object properties.
Common Mistakes and Tips
- Forgetting to update the loop counter — this can lead to infinite loops.
- Confusing
for...ofwithfor...in— they serve different purposes. - Use
breakandcontinuewisely for better control and performance.
Recognize the important boundary
for...in visits enumerable property keys, not array values. An endless loop can freeze the main thread.
Try a small variation
JavaScript · original source for practice
const marks = [70, 80];
for (const mark of marks) console.log(mark);
Your task: Replace 70,80 with 60,90. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The traversal reads each value from the edited collection.
JavaScript · complete worked variation
const marks = [60, 90];
for (const mark of marks) console.log(mark);
Expected output
60
90Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const marks = [70, 80];
for (const mark of marks) console.log(mark);
Keep the useful idea
A loop repeats instructions. for suits a count, while suits a changing condition, and for...of visits array values. A school report should choose the traversal that matches its data rather than copying a loop mechanically.
Check your variation against this explanation: The traversal reads each value from the edited collection.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.