Looping statements are used to execute the same block of code repeatedly as long as a specified condition is satisfied.
- Repetition — Allow the same block of code to execute multiple times without rewriting it.
- Efficiency — Reduce code duplication.
- Processing data — Useful for iterating through arrays, lists, and other collections.
- Automation — Perform repetitive tasks automatically.
Types of Looping Statements
Very often, when writing code, you want the same block of code to run repeatedly. Instead of writing several similar lines of code, you can use loops to perform these tasks.
1️⃣ For loop
The for loop is used when you know in advance how many times the code should execute.
// Syntax
for (initialisation; condition; increment/decrement) {
// Code to be executed
}
// Example
for (var i = 1; i <= 10; i++) {
console.log(i);
}
Components of a for loop:
- Initialisation — Initializes the loop variable.
- Condition — Determines whether the loop should continue.
- Increment/Decrement — Updates the loop variable after each iteration.
2️⃣ While loop
The while loop executes a block of code repeatedly as long as the specified condition is true.
// Syntax
initialisation;
while (condition) {
// Code to be executed
// Update variable
}
// Example
var i = 0;
while (i <= 10) {
console.log(i);
i = i + 1;
}
Note
The condition is checked before executing the loop body. Therefore, the loop may not execute even once if the condition is initially false.
3️⃣ Do...while loop
The do...while loop executes the code block at least once, even if the condition is false, because the condition is checked after executing the code.
// Syntax
initialisation;
do {
// Code to be executed
// Update variable
} while (condition);
// Example
var i = 0;
do {
console.log(i);
i = i + 1;
} while (i <= 10);
Note
Unlike the
whileloop, thedo...whileloop checks the condition after executing the code block.
Quick Comparison
| Loop | Condition Check | Minimum Executions |
|---|---|---|
| for | Before execution | 0 |
| while | Before execution | 0 |
| do...while | After execution | 1 |
Comments
Join the discussionNo comments yet. Be the first to comment.
Decode Javascript
Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.
