Trace a while Loop
Trace a while Loop
A while loop checks its condition before entering the body. An attendance counter must change toward the stopping condition; otherwise the loop repeats without making progress.
Before this topic, review Trace a for Loop if its terms are unfamiliar.
What you’ll learn
- Explain trace a while 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 count reaches 3, then the next condition check stops the loop.
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
let count = 0;
while (count < 2) {
count++;
}
console.log(count);
Expected output
2Run in JavaScript compiler →Introduction to JavaScript While Loop
The while loop in JavaScript is a control structure that lets you repeat a block of code as long as a condition remains true. It's one of the fundamental building blocks for creating dynamic behavior and automating repetitive tasks.
Think of it like a repeating question: "Should I continue?" If the answer is yes (i.e., the condition is true), the loop runs again. If not, it stops right there.
Syntax of a While Loop
while (condition) {
// code block to execute
}
The condition is evaluated before the loop body runs. If it's true, the body executes. If false, the loop exits immediately.
Basic Example
let i = 0;
while (i < 5) {
console.log("Number is: " + i);
i++;
}
Number is: 0
Number is: 1
Number is: 2
Number is: 3
Number is: 4
In this example, i starts at 0. The loop continues while i < 5. With each pass, we print the number and increase i by 1. Once i reaches 5, the loop stops.
Infinite Loop (What Not to Do)
while (true) {
console.log("This will run forever!");
}
This will run forever!
This will run forever!
This will run forever!
This will run forever!
Be careful! If the condition never becomes false, the loop will never end — this is called an infinite loop. It can freeze your browser or crash your program.
Using While Loop with User Input
let password;
while (password !== "secret123") {
password = prompt("Enter the password:");
}
alert("Access granted!");
Access granted!
This loop keeps prompting the user until they type secret123. Once the correct password is entered, the loop exits, and access is granted.
Looping Through Arrays (with While)
let fruits = ["apple", "banana", "cherry"];
let index = 0;
while (index < fruits.length) {
console.log(fruits[index]);
index++;
}
apple
banana
cherry
apple
banana
cherry
Although for loops are more common for arrays, while loops offer greater flexibility when you're not sure how many iterations you need in advance.
Nested While Loops
let row = 1;
while (row <= 3) {
let col = 1;
while (col <= 3) {
console.log(`Row ${row}, Column ${col}`);
col++;
}
row++;
}
Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
Row 3, Column 1
Row 3, Column 2
Row 3, Column 3
This example demonstrates a grid-like iteration using nested while loops — often used in matrix operations, games, or simulations.
Break and Continue in While Loop
Using break to Exit Early
let x = 1;
while (x <= 10) {
if (x === 5) break;
console.log(x);
x++;
}
1
2
3
4
The break statement forces the loop to stop completely when x === 5.
Using continue to Skip Iterations
let y = 0;
while (y < 5) {
y++;
if (y === 3) continue;
console.log(y);
}
1
2
4
5
When y === 3, the continue skips that iteration — meaning 3 doesn’t get printed.
When to Use a While Loop
Choose a while loop when:
- You don’t know beforehand how many times you need to repeat the task.
- You’re waiting for a user input or a specific condition to become false.
- You need more manual control over the loop counter or conditions.
Common Pitfalls
- Forgetting to update the loop variable: Can lead to infinite loops.
- Using complex conditions: Always ensure they eventually evaluate to false.
- Misusing break/continue: Use wisely to control logic, but not as a substitute for good structure.
Recognize the important boundary
A false initial condition runs the body zero times. Keep necessary updates reachable when using continue.
Try a small variation
JavaScript · original source for practice
let count = 0;
while (count < 2) {
count++;
}
console.log(count);
Your task: Replace < 2 with < 3. 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 count reaches 3, then the next condition check stops the loop.
JavaScript · complete worked variation
let count = 0;
while (count < 3) {
count++;
}
console.log(count);
Expected output
3Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
let count = 0;
while (count < 2) {
count++;
}
console.log(count);
Keep the useful idea
A while loop checks its condition before entering the body. An attendance counter must change toward the stopping condition; otherwise the loop repeats without making progress.
Check your variation against this explanation: The count reaches 3, then the next condition check stops the loop.
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.