We can achieve many different outcomes with while loops.
For example, we can print print all the numbers from 0
through 4
:
let i = 0;
while(i < 5) {
console.log(i);
i++;
}
The output of this program is:
0
1
2
3
4
And this is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 5
true? <=> Is 0 < 5
true? Yes.
b. console.log(i); => Output: 0
c. i++; => i = 1
1. Second iteration:
a. Is i < 5
true? <=> Is 1 < 5
true? Yes.
b. console.log(i); => Output: 1
c. i++; => i = 2
2. Third iteration:
a. Is i < 5
true? <=> Is 2 < 5
true? Yes.
b. console.log(i); => Output: 2
c. i++; => i = 3
3. Forth iteration:
a. Is i < 5
true? <=> Is 3 < 5
true? Yes.
b. console.log(i); => Output: 3
c. i++; => i = 4
4. Fifth iteration:
a. Is i < 5
true? <=> Is 4 < 5
true? Yes.
b. console.log(i); => Output: 4
c. i++; => i = 5
5. Sixth iteration:
a. Is i < 5
true? <=> Is 5 < 5
true? No.
b. Exit the loop.
Assignment
Let's print all numbers from 3
to 10
using a while loop.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of while loops in JavaScript. While loops are a fundamental control structure that allows us to execute a block of code repeatedly as long as a specified condition is true. This is particularly useful in scenarios where we need to perform repetitive tasks, such as iterating over a range of numbers or processing items in a collection.
A while loop in JavaScript has the following syntax:
while (condition) {
// code to be executed
}
The loop will continue to execute the code block as long as the condition evaluates to true. If the condition is false initially, the code block will not execute at all.
Let's start with a simple example to print numbers from 0 to 4:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, the loop initializes the variable i
to 0 and continues to print the value of i
and increment it by 1 until i
is no longer less than 5.
To understand while loops better, let's break down the key concepts:
These three steps are crucial for preventing infinite loops, where the condition never becomes false.
Let's apply these concepts to solve the assignment: printing numbers from 3 to 10.
let i = 3;
while (i <= 10) {
console.log(i);
i++;
}
In this example:
i
to 3.i <= 10
ensures the loop runs as long as i
is less than or equal to 10.i
by 1 in each iteration.Here are some common mistakes to avoid and best practices to follow:
While loops can be combined with other control structures for more complex logic. For example, using a break statement to exit the loop early:
let i = 3;
while (i <= 10) {
if (i === 7) {
break; // Exit the loop when i is 7
}
console.log(i);
i++;
}
This loop will print numbers from 3 to 6 and then exit when i
is 7.
Here is the complete code to print numbers from 3 to 10 using a while loop:
let i = 3;
while (i <= 10) {
console.log(i);
i++;
}
This code is straightforward and demonstrates the basic use of a while loop.
When debugging while loops, consider the following tips:
console.log
to print variable values and understand the loop's behavior.For testing, you can write test cases to ensure the loop produces the expected output:
function printNumbers() {
let i = 3;
let result = [];
while (i <= 10) {
result.push(i);
i++;
}
return result;
}
// Test case
console.assert(JSON.stringify(printNumbers()) === JSON.stringify([3, 4, 5, 6, 7, 8, 9, 10]), 'Test failed');
When approaching problems involving loops:
In this lesson, we covered the basics of while loops in JavaScript, including their syntax, key concepts, and common use cases. We also discussed common pitfalls, best practices, and advanced techniques. Mastering while loops is essential for writing efficient and effective code in many programming scenarios.
Keep practicing and exploring more complex problems to deepen your understanding of while loops and other control structures.
For further reading and practice, check out the following resources: