JavaScript While Loop
In JavaScript, the while loop is used to run a block of code again and again, as long as a certain condition is true. It’s helpful when you don’t know ahead of time how many times the loop should run.
You can use a while loop in many situations, such as:
- Repeating tasks: For example, printing numbers, checking user input, or waiting for a value to change.
- Checking conditions: Keep looping while something is true, like count <= 10.
- Creating infinite loops: A while loop can run forever if the condition never becomes false. Be careful with these!
- Breaking out manually: You can use break inside a loop to stop it when a certain condition is met.
The while loop checks the condition before each repetition. If the condition is false right from the start, the code inside the loop won't run at all.
What You'll Learn
This guide introduces the basics of the while loop in JavaScript. You'll understand the syntax, how it works, and apply it with real examples.
Understanding the while Loop
The basic syntax for a while loop in JavaScript looks like this:
while (condition) {
// Code block to execute
// Do something
}
while (condition) {
// Code block to execute
// Do something
}
- condition: This is the expression that gets checked before each loop run. As long as it evaluates to true, the loop keeps running.
- Code block: The set of statements inside the curly braces { } that run repeatedly while the condition is true.
Be careful — if the condition never becomes false, the loop will run forever. This is called an infinite loop and can crash your program or browser!
Example 1: Simple While Loop
In this example, we will print the numbers 1 to 5 using a while loop in JavaScript.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
How It Works:
- let i = 1: This initializes the variable i to 1.
- while (i <= 5): This condition keeps the loop running as long as i is less than or equal to 5.
- console.log(i): This prints the current value of i to the console.
- i++: This increases the value of i by 1 after each loop iteration.
- Important: If you forget to update the value of i, the condition will always be true, and the loop will run forever. This creates an infinite loop.
Output
1
2
3
4
5
1
2
3
4
5
Example 2: Print Even Numbers from 1 to 20
In this example, we will print the even numbers from 1 to 20 using a while loop in JavaScript.
let i = 2;
while (i <= 20) {
console.log(i);
i += 2;
}
let i = 2;
while (i <= 20) {
console.log(i);
i += 2;
}
How It Works:
- let i = 2: This initializes the variable i to 2 (the first even number).
- while (i <= 20): This condition ensures the loop runs as long as i is less than or equal to 20.
- console.log(i): This prints the current value of i (the even numbers).
- i += 2: This increments i by 2 after each iteration, ensuring that only even numbers are printed (2, 4, 6, 8, etc.).
- Important: Make sure the increment matches the step you want (in this case, 2) to print even numbers. Incorrect increments may cause unexpected results.
Output
2
4
6
8
10
12
14
16
18
20
2
4
6
8
10
12
14
16
18
20
Example 3: Sum of Digits
In this example, we will calculate the sum of the digits of a number (e.g., 1234) using a while loop in JavaScript.
let num = 1234;
let sum = 0;
while (num > 0) {
let digit = num % 10; // Get the last digit
sum += digit; // Add the digit to the sum
num = Math.floor(num / 10); // Remove the last digit
}
console.log("Sum of digits is:", sum);
let num = 1234;
let sum = 0;
while (num > 0) {
let digit = num % 10; // Get the last digit
sum += digit; // Add the digit to the sum
num = Math.floor(num / 10); // Remove the last digit
}
console.log("Sum of digits is:", sum);
How It Works:
- let num = 1234: This initializes the variable num with the number whose digits we want to sum.
- let sum = 0: This initializes the sum variable to 0, which will hold the sum of the digits.
- while (num > 0): The loop runs as long as the number num is greater than 0 (i.e., until all digits are processed).
- let digit = num % 10: This gets the last digit of the number using the modulus operator (e.g., 1234 % 10 = 4).
- sum += digit: Adds the last digit to the sum.
- num = Math.floor(num / 10): Removes the last digit from num (e.g., 1234 becomes 123 after this operation).
- Important: If you forget to update the value of num, the loop will run infinitely, as the number will never become 0.
Output
Sum of digits is: 10
Sum of digits is: 10
Example 4: Infinite Loop
In this example, we will create an infinite loop using a while loop in JavaScript. Be cautious—this loop will run endlessly unless manually stopped!
while (true) {
console.log("This is an infinite loop!");
// To stop the loop, press Ctrl + C (Windows/Linux) or Command + C (Mac) in the terminal.
}
while (true) {
console.log("This is an infinite loop!");
// To stop the loop, press Ctrl + C (Windows/Linux) or Command + C (Mac) in the terminal.
}
How It Works:
- while (true): The condition is set to true, so the loop will always evaluate to true and continue running endlessly.
- console.log("This is an infinite loop!"): This line prints the message to the console every time the loop runs.
- Important: This loop will continue to run indefinitely, which can freeze your browser or application. To stop it, follow the instructions based on your operating system:
- Windows: Press Ctrl + C in the terminal or command prompt to stop the loop.
- Mac: Press Command + C in the terminal to stop the loop.
- Linux: Press Ctrl + C in the terminal to stop the loop.
Output
This is an infinite loop!
This is an infinite loop!
... (and it keeps printing indefinitely)
This is an infinite loop!
This is an infinite loop!
... (and it keeps printing indefinitely)
Exercises
1. Print numbers from 1 to 10.
let i = 1;
while (i <= 10) {
console.log(i);
i++;
}
let i = 1;
while (i <= 10) {
console.log(i);
i++;
}
2. Print the sum of numbers from 1 to a given number (e.g., 10).
let num = 10;
let sum = 0;
let i = 1;
while (i <= num) {
sum += i;
i++;
}
console.log("The sum is:", sum);
let num = 10;
let sum = 0;
let i = 1;
while (i <= num) {
sum += i;
i++;
}
console.log("The sum is:", sum);
3. Print odd numbers from 1 to 20.
let i = 1;
while (i <= 20) {
console.log(i);
i += 2;
}
let i = 1;
while (i <= 20) {
console.log(i);
i += 2;
}
*Try changing conditions and values to see how loops behave!
Frequently Asked Questions
What is a while loop in JavaScript?
What is a while loop in JavaScript?
A while loop in JavaScript is used to repeatedly execute a block of code as long as a specified condition evaluates to true.
How does the condition work in a while loop?
How does the condition work in a while loop?
The condition in a while loop is evaluated before each iteration. If the condition is true, the loop will continue executing. If it's false, the loop will stop.
Can I create an infinite loop with a while loop?
Can I create an infinite loop with a while loop?
Yes, if the condition in the while loop never becomes false, it will result in an infinite loop. Be cautious to ensure that the loop condition will eventually evaluate to false.
What happens if I forget to update the loop condition?
What happens if I forget to update the loop condition?
If you forget to update the condition inside the loop (e.g., forgetting to increment a counter), the loop will run indefinitely, potentially freezing your program.
Can I use a while loop to iterate through arrays?
Can I use a while loop to iterate through arrays?
Yes, a while loop can be used to iterate through arrays, but it's generally recommended to use a for loop because it's more concise and easier to manage for array iteration.
What's Next?
Up next, we’ll dive into the do...while loop — a variation of the while loop that ensures the code inside the loop runs at least once before checking the condition. It’s especially useful when you want to guarantee that a block of code executes before any validation.