- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Calling the function
- Class
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Else
- Else if
- Equals operator
- Extend
- Filter
- For loop
- function
- Function name
- Greater than
- Head element
- If statement
- Less than
- Map
- Methods
- Numbers
- Overriding methods
- Parameters
- Reduce
- Removing an element
- Replace
- Sort
- Splice
- String
- Substring
- Tile
- while-loops
JAVASCRIPT
JavaScript While Loop: Syntax, Usage, and Examples
The JavaScript while loop is a control flow statement that runs a block of code for as long as a specified condition is true. The while loop will execute the code in the body of the loop until the specified condition becomes false.
How to Use the While Loop in JavaScript
The syntax for using a while loop in JavaScript is straightforward. Here's the basic structure:
while (condition) {
// Execute these statements as long as the condition is true
statements;
}
while
: The keyword to initiate the while loop.condition
: A boolean expression that the while loop evaluates totrue
orfalse
before each iteration. If the expression evaluates totrue
, the loop's body executes. As soon as the expression evaluates tofalse
, the loop terminates.statements
: JavaScript statements to execute as long as the condition evaluates totrue
.
When to Use the While Loop in JavaScript
While loops are ideal when the end condition is unknown in advance.
Continuous Execution
JavaScript while loops are ideal for tasks that require continuous checking and execution until a particular condition changes.
let response;
while (!response) {
response = prompt("Please enter your name:");
}
console.log("Hello, " + response + "!");
Processing Items
While loops are also useful for processing items in an array when the processing might affect the length of the array.
let numbers = [1, 2, 3, 4, 5, 6];
while (numbers.length > 0) {
let item = numbers.pop(); // Removes the last element
console.log('Processing:', item);
}
Examples of While Loops in JavaScript
User Input Validation
While loops can ensure that user input meets certain criteria before proceeding.
let age;
while (!age || age < 18) {
age = prompt("Please enter your age (you must be 18 or older to proceed):");
}
console.log("Access granted.");
Data Streaming
While loops can enable data streaming, where data often comes in chunks and processing continues until the stream ends.
let dataAvailable = true;
while (dataAvailable) {
let data = stream.getNextChunk();
if (data) {
processData(data);
} else {
dataAvailable = false;
}
}
Runtime Control
In game development, for example, while loops can keep a game running until a player decides to quit or achieves a certain goal.
let inGame = true;
while (inGame) {
// Game logic
if (playerWantsToQuit()) {
inGame = false;
}
}
Learn More About the While Loop in JavaScript
Do While Loop in JavaScript
A variation of the while loop is the do-while loop. Do-while loops guarantee that the loop's body executes at least once before testing the condition for the first time.
let result;
do {
result = performAction();
} while (result !== 'success');
Infinite Loops
In an infinite loop, the condition of the while loop is always true and never becomes false. Infinite loops can cause an application to crash or stop responding.
// Don't try this at home
let count = 0;
while (count < 5) {
console.log(count);
}
Combining Loops with Other Control Structures
You can combine while loops with other control structures like if statements to handle complex logic within a loop.
let number = 0;
while (number < 20) {
if (number % 2 === 0) {
console.log(number + " is even");
} else {
console.log(number + " is odd");
}
number++;
}
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.