The JavaScript while loop runs code as long as a condition stays true. You can use it to repeat tasks like counting numbers or checking user inputs.
Table of Content
- Understand the
whileLoop in JavaScript - No-Body
whileLoop (Without Braces) - Use the
breakandcontinueinwhileLoop - The
whilevsdo…whileLoop - How to Avoid Infinite Loops in a
whileLoop - Example 1: Sum of User Input Values
- Example 2: Nested While Loops
- Example 3: Find All Prime Numbers in a Given Range
- Example 4: Simulates a Progress Bar
- Wrapping Up
- FAQ’s
Understand the while Loop in JavaScript
The while loop is a control flow tool that repeats code as long as a given condition is true.
The loop keeps running while the condition stays true. It terminates if the condition is evaluated as false, and the program continues with the next statement following the loop.
Here is the syntax:
while (condition) {
// code block to be executed
}The condition is evaluated before each iteration. If the condition is true, the code block executes; otherwise, the loop ends.
Here is a quick example:
A basic use of the while loop is to count numbers within a specified range. For instance, to print numbers from 1 to 5:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}The output:
1
2
3
4
5
This loop initializes i to 1 and increments it until it exceeds 5. It prints each value of i within the process.
No-Body while Loop (Without Braces)
You can omit the braces {} for the loop body if you only have one statement to execute. This can make the code more concise but may reduce readability if overused.
while (condition)
statement;- The condition is the boolean expression that is checked before each iteration.
- The Statement is the code executed as long as the condition is true. You must use braces if there are multiple statements.
Here is an example:
let i = 90;
while (i <= 100)
console.log(i++);The output:
90
91
92
93
94
95
96
97
98
99
100
In this code:
- The loop runs as long as
iis less than or equal to 5. - The statement
console.log(i++)is executed on each iteration. - The lack of braces means that only the
console.log(i++)statement is considered part of the loop body.
Use the break and continue in while Loop
You can use break and continue in while loops to control the flow. These help you stop a loop early or skip a step.
The break ends the loop right away. It does not check the condition again. Here is an example:
let count = 0;
while (count < 10) {
if (count === 5) {
break;
}
console.log(count);
count++;
}This prints:
0
1
2
3
4
The loop stops when count reaches 5.
Continue skips the rest of the current loop step. It goes back to the condition and checks if it should keep going.
Here is an example:
let count = 0;
while (count < 5) {
count++;
if (count === 3) {
continue;
}
console.log(count);
}This prints:
1
2
4
5
The number 3 does not print because continue skips the console.log() for that step.
The while vs do…while Loop
The while loop and the do...while loop both repeat code while a condition is true. The key difference is when the condition runs.
While loop checks the condition before the first run. If the condition is false, the loop doesn’t run.
Here is an example:
let count = 0;
while (count > 0) {
console.log(count);
count--;
}This runs zero times because count > 0 is false right away.
Do…while loop runs the code first, then checks the condition. It always runs at least once.
Example:
let count = 0;
do {
console.log(count);
count--;
} while (count > 0);This prints 0 one time, even though the condition is false.
How to Avoid Infinite Loops in a while Loop
You need to set up a clear exit condition to avoid infinite loops in a while loop. The loop will run forever if the condition never becomes false.
Here are the steps you can follow:
Write a condition that can change based on something inside the loop. For example:
let count = 0;
while (count < 5) {
console.log(count);
count++;
}Output:
0
1
2
3
4
The loop stops when count reaches 5. Without count++, the loop would run forever.
You need to change the variable that controls the loop. If that does not happen, the loop condition stays true. Like this:
let input = '';
while (input !== 'exit') {
input = prompt('Type "exit" to stop');
}The user controls the exit. The loop ends when they type the right word.
You can include a break inside the loop in case something goes wrong. For example:
let count = 0;
while (true) {
if (count >= 10) break;
console.log(count);
count++;
}The output:
0
1
2
3
4
5
6
7
8
9
This kind of loop can help when the end condition is complex but you still want control.
Example 1: Sum of User Input Values
You can use a while loop to add numbers entered by the user. The loop continues until the user types a negative number. Each valid number adds to the total.
Examples:
let sum = 0;
let num = 0;
while (num >= 0) {
num = parseInt(prompt("Enter a number:"));
if (num >= 0) {
sum += num;
}
}
console.log("The total sum is: " + sum);This helps you collect and add numbers until the user chooses to stop.
Example 2: Nested While Loops
A nested while loop means you put one while loop inside another. The outer loop runs first. The inner loop runs completely for each turn of the outer loop.
Here is a simple example:
let i = 1;
while (i <= 3) {
let j = 1;
while (j <= 2) {
console.log(`i = ${i}, j = ${j}`);
j++;
}
i++;
}This prints:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
The outer loop controls i and the inner loop controls j. For each value of i, the j loop starts fresh and runs two times.
Example 3: Find All Prime Numbers in a Given Range
This example shows you how to use a while loop to find all prime numbers in a given range.
let num = 2;
let primes = [];
while (num <= 100) {
let isPrime = true;
let divisor = 2;
while (divisor <= Math.sqrt(num)) {
if (num % divisor === 0) {
isPrime = false;
break;
}
divisor++;
}
if (isPrime) {
primes.push(num);
}
num++;
}
console.log(primes);The output:
[
2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89,
97
]
Here is how it works:
- We use two nested
whileloops. The outer loop checks numbers from 2 to 100. - The inner loop checks if the current number is divisible by any number less than or equal to the square root of the current number.
- If no divisors are found, the number is added to the
primesarray.
Example 4: Simulates a Progress Bar
This example simulates a progress bar using a while loop to iterate through and display a simple percentage-based progress.
let progress = 0;
const target = 100;
while (progress < target) {
progress += 10;
console.clear();
console.log(`Progress: [${'='.repeat(progress / 10)}${' '.repeat((target - progress) / 10)}] ${progress}%`);
// Simulate time delay (e.g., loading or task)
for (let i = 0; i < 1e6; i++) {}
}Output:
Progress: [= ] 10%
Progress: [== ] 20%
Progress: [=== ] 30%
Progress: [==== ] 40%
Progress: [===== ] 50%
Progress: [====== ] 60%
Progress: [======= ] 70%
Progress: [======== ] 80%
Progress: [========= ] 90%
Progress: [==========] 100%
How it works:
- The loop continues until the
progressreaches 100. - Each iteration adds 10% to the progress and updates the progress bar output.
- The
console.clear()is used to clear the screen and print the updated progress bar. - The inner loop is used to simulate a delay for visualization (in real-world cases, this could be replaced with actual work being done).
Wrapping Up
You learned how the while loop in JavaScript allows code to repeat as long as a given condition is true.
Here is a quick recap:
- The
whileloop repeats code as long as the condition is true. - You can sum values or count with the
whileloop. - Nested
whileloops help in more complex scenarios. - Using
breakandcontinueallows you to control loop flow. - The
do...whileloop ensures at least one iteration.
Thank you for reading. Here are JavaScript tutorials if you need to read more.
FAQ’s
What is the syntax of a while loop in JavaScript?
while (condition) {
// code block to be executed
}
The loop will execute the code block as long as the specified condition evaluates to true. The loop stops once the condition is false.
How do you stop a while loop in JavaScript?
let count = 0;
while (count < 10) {
if (count === 5) {
break;
}
console.log(count);
count++;
}
This will stop the loop when count reaches 5.
What is the difference between a while loop and a do...while loop in JavaScript?
- while loop: The condition is checked before the first iteration. If the condition is false initially, the loop will not run at all.
- do...while loop: The code inside the loop runs at least once before the condition is checked. Even if the condition is false initially, the loop will execute once.
let count = 0;
while (count > 0) {
console.log(count);
count--;
}
Example of a do...while loop:
let count = 0;
do {
console.log(count);
count--;
} while (count > 0);
How can you use a while loop to sum user input values in JavaScript?
let sum = 0;
let num = 0;
while (num >= 0) {
num = parseInt(prompt("Enter a number:"));
if (num >= 0) {
sum += num;
}
}
console.log("The total sum is: " + sum);
This loop adds the entered numbers to the sum and stops when the user inputs a negative number.
Can you omit braces in a while loop in JavaScript?
while (condition)
statement;
Similar Reads
String Operators in JavaScript help you work with text. You can join, build, or change strings. Most of what you…
The development of full-featured and interesting pages cannot be done without JavaScript which makes it possible to animate plain HTML…
JavaScript toReversed returns a new array with the reversed order of its elements. It does not change the original array…
Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…
JavaScript moves fast, and new features come. Some browsers do not support these features and cause issues for users. Developers…
The assignment operator in JavaScript stores and updates values. It helps you hold data in a variable and change it…
The current essay is devoted to the basic principles and introduction of JavaScript. This language no longer needs to be…
You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…
Code mistakes used to slip by without a warning. That made bugs hard to trace and fix. JavaScript "use strict"…
Bitwise operators work with binary data at the bit level in JavaScript. They process numbers in binary form and return…