A while loop allows your program to perform a set of instructions as long as a condition is satisfied.
Here is the structure of a while loop:
while(condition) {
instruction1
instruction2
...
}
Let's check an example:
let count = 1;
while(count <= 5) {
console.log("I made a mistake");
count++;
}
console.log("Finished!");
The output of this program is:
I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!
And this is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable count = 1
1. First iteration:
a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
b. console.log("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 2
2. Second iteration:
a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
b. console.log("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 3
3. Third iteration:
a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
b. console.log("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 4
4. Forth iteration:
a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
b. console.log("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 5
5. Fifth iteration:
a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
b. console.log("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 6
6. Sixth iteration:
a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
b. Terminate the loop.
7. console.log("Finished!"); => Output: Finished!
Pro Tip:
A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.
Assignment
Let's print "I promise to learn coding" 5 times using a loop.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the while loop in JavaScript. The while loop is a fundamental control structure that allows you to repeat a block of code as long as a specified condition is true. This is particularly useful in scenarios where the number of iterations is not known beforehand, such as reading data from a file until the end is reached or processing user input until a certain condition is met.
The basic syntax of a while loop is straightforward:
while(condition) {
// code to be executed
}
The loop will continue to execute the block of code inside it as long as the condition evaluates to true. If the condition is false initially, the code inside the loop will not execute at all.
Let's break down the key concepts and techniques involved in using a while loop:
Here is a simple example to illustrate these concepts:
let count = 1;
while(count <= 5) {
console.log("I made a mistake");
count++;
}
console.log("Finished!");
Let's look at a few more examples to understand the versatility of the while loop:
let count = 5;
while(count > 0) {
console.log(count);
count--;
}
console.log("Blast off!");
In this example, the loop counts down from 5 to 1 and then prints "Blast off!".
let userInput;
while(userInput !== "exit") {
userInput = prompt("Enter something (type 'exit' to quit):");
console.log("You entered: " + userInput);
}
console.log("Goodbye!");
This example demonstrates how a while loop can be used to repeatedly prompt the user for input until they type "exit".
Here are some common mistakes to avoid when using while loops:
Best practices for writing clear and efficient while loops include:
Once you are comfortable with basic while loops, you can explore more advanced techniques such as:
break to exit the loop early or continue to skip the current iteration and proceed to the next one.Here is an example of a nested loop:
let i = 1;
while(i <= 3) {
let j = 1;
while(j <= 3) {
console.log(`i = ${i}, j = ${j}`);
j++;
}
i++;
}
Let's implement the assignment to print "I promise to learn coding" 5 times using a while loop:
let count = 1; // Initialize the counter variable
while(count <= 5) { // Loop condition
console.log("I promise to learn coding"); // Print the message
count++; // Increment the counter
}
In this code, we initialize the counter variable count to 1. The loop runs as long as count is less than or equal to 5. Inside the loop, we print the message and then increment the counter.
When debugging while loops, consider the following tips:
console.log statements to track the values of variables and the flow of execution.To test the loop, you can write test cases that verify the expected output for different initial conditions and loop conditions.
When approaching problems that involve loops, consider the following strategies:
In this lesson, we covered the basics of the while loop in JavaScript, including its syntax, key concepts, and common use cases. We also discussed best practices, advanced techniques, and debugging tips. Mastering the while loop is essential for writing efficient and effective code, especially in scenarios where the number of iterations is not known beforehand.
Keep practicing and exploring different applications of the while loop to deepen your understanding and improve your coding skills.
For further reading and practice, check out the following resources:
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE