Loops are one of the most powerful features in JavaScript. They allow developers to execute a block of code repeatedly without writing the same code multiple times.
Whether you're processing arrays, generating
reports, validating data, or automating repetitive tasks, loops help make your
code cleaner, shorter, and more efficient.
In this guide, you'll learn how JavaScript
loops work, including for, while, and do...while loops, along
with practical examples and best practices.
What Are Loops in JavaScript?
A loop is a programming structure that
repeats a block of code as long as a specified condition is true.
Instead of writing:
console.log("Hello");console.log("Hello");console.log("Hello");console.log("Hello");console.log("Hello");
You can write:
for (let i = 1; i <= 5; i++) { console.log("Hello");}
This produces the same result with much less
code.
Why Use Loops?
Loops help developers:
·
Reduce repetitive
code.
·
Process large
amounts of data efficiently.
·
Iterate through
arrays and objects.
·
Automate
repetitive tasks.
·
Improve code
readability and maintainability.
The for Loop
The for loop
is the most commonly used loop in JavaScript. It is ideal when you know in
advance how many times the loop should run.
Syntax
for (initialization; condition; increment) { // code to execute}
Components
·
Initialization: Runs once before the loop starts.
·
Condition: Checked before each iteration.
·
Increment/Decrement: Updates the loop variable after each iteration.
Example
for (let i = 1; i <= 5; i++) { console.log(i);}
Output
12345
Counting Backward with a for Loop
You can also count in reverse.
for (let i = 5; i >= 1; i--) { console.log(i);}
Output
54321
Using a for Loop with Arrays
Loops are commonly used to process array
elements.
let fruits = ["Apple", "Banana", "Orange"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}
Output
AppleBananaOrange
The while
Loop
A while
loop executes as long as its condition remains true.
Syntax
while (condition) { // code to execute}
Example
let count = 1; while (count <= 5) { console.log(count); count++;}
Output
12345
The condition is checked before each
iteration.
When to Use a while Loop
Use a while
loop when:
·
You don't know
exactly how many iterations are needed.
·
The loop depends
on user input.
·
The stopping
condition is determined during execution.
Example
let passwordCorrect = false; while (!passwordCorrect) { // Ask user for password passwordCorrect = true;}
The do...while
Loop
The do...while
loop is similar to a while loop, but it executes the code block at least once
before checking the condition.
Syntax
do { // code to execute} while (condition);
Example
let number = 1; do { console.log(number); number++;} while (number <= 5);
Output
12345
Difference Between while and do...while
while Loop
let x = 10; while (x < 5) { console.log(x);}
Output:
No output because the condition is false from
the start.
do...while Loop
let x = 10; do { console.log(x);} while (x < 5);
Output:
10
The code executes once before the condition
is checked.
The break
Statement
The break
statement immediately exits a loop.
Example
for (let i = 1; i <= 10; i++) { if (i === 5) { break; } console.log(i);}
Output
1234
The loop stops when i reaches
5.
The continue
Statement
The continue
statement skips the current iteration and moves to the next one.
Example
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i);}
Output
1245
The value 3 is skipped.
Nested Loops
A loop can exist inside another loop.
Example
for (let row = 1; row <= 3; row++) { for (let col = 1; col <= 3; col++) { console.log(`Row ${row}, Column ${col}`); } }
Output
Row 1, Column 1Row 1, Column 2Row 1, Column 3...
Nested loops are commonly used for tables,
grids, and matrix operations.
Common Loop Mistakes
Infinite Loops
An infinite loop occurs when the condition
never becomes false.
Incorrect:
let i = 1; while (i <= 5) { console.log(i);}
The variable i is
never updated, causing the loop to run forever.
Correct:
let i = 1; while (i <= 5) { console.log(i); i++;}
Off-by-One Errors
Incorrect:
for (let i = 0; i <= array.length; i++) { console.log(array[i]);}
This accesses an index that doesn't exist.
Correct:
for (let i = 0; i < array.length; i++) { console.log(array[i]);}
Best Practices for Using Loops
Choose the Right Loop
·
Use for when the number of iterations is known.
·
Use while when the stopping condition is dynamic.
·
Use do...while when the code must execute at least once.
Avoid Deep Nesting
Too many nested loops can make code difficult
to understand and may impact performance.
Keep Conditions Clear
Write conditions that are easy to read and
maintain.
Prevent Infinite Loops
Always ensure loop variables are updated
correctly.
Real-World Example
Calculating the sum of numbers from 1 to 10:
let sum = 0; for (let i = 1; i <= 10; i++) { sum += i;} console.log(sum);
Output
55
This demonstrates how loops can automate
repetitive calculations.
Conclusion
Loops are a fundamental part of JavaScript
programming. The for, while, and do...while loops help
developers automate repetitive tasks, process data efficiently, and write
cleaner code.
Understanding when and how to use each type
of loop will make your programs more powerful, efficient, and easier to
maintain. As you continue learning JavaScript, mastering loops will open the
door to working with arrays, objects, APIs, and more advanced programming
concepts.
