JavaScript loops let you run the same block of code more than once.
A shopping website can loop through products. A menu can loop through navigation items. A dashboard can process rows of data. A form can check several fields without repeating the same code manually.
In this lesson, you will learn the most useful JavaScript loops, when to use each one, how break and continue work, and how to avoid common loop mistakes.
Course Home: JavaScript Tutorial for Beginners
Previous Lesson: JavaScript if else Explained
Next Lesson: JavaScript Functions Explained for Beginners
Quick Answer
A JavaScript loop repeats code while a rule allows it.
A simple for loop looks like this:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
The main loops beginners should know are:
forwhiledo...whilefor...of
You will also learn:
breakcontinue- nested loops
- looping through arrays
- how infinite loops happen
What Is a Loop in JavaScript?
A loop repeats a block of code.
Without a loop, you might write:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
A loop can do the same job with less repeated code:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
The result is still:
1
2
3
4
5
Loops become much more useful when you work with arrays, products, API data, tables, lists, and repeated calculations.
Why JavaScript Loops Matter
Websites often work with groups of values.
For example, you may need to:
- Display every product in an array
- Add several prices together
- Check every form field
- Print numbers from 1 to 10
- Search a list for a matching item
- Repeat a task until a condition changes
- Build rows from data
- Process API results
- Show menu items
- Count completed tasks
Writing separate code for every item would be slow and difficult to maintain.
Loops let one block of code handle many values.
Main JavaScript Loop Types
The main loops covered in this tutorial are:
| Loop | Best beginner use |
|---|---|
for | Repeat a known number of times |
while | Repeat while a condition stays true |
do...while | Run once, then repeat while a condition stays true |
for...of | Loop through values in arrays and other iterable collections |
You will also see for...in, but it is mainly used for object property keys rather than normal array values.
JavaScript for Loop
The for loop is one of the most common JavaScript loops.
Syntax:
for (initialization; condition; update) {
// repeated code
}
Example:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
The loop has three main parts:
let i = 1
starts the counter.
i <= 5
decides whether the loop should continue.
i++
increases the counter after each loop.
Step-by-Step for Loop Example
Consider:
for (let i = 1; i <= 3; i++) {
console.log(i);
}
First Loop
i starts at:
1
JavaScript checks:
i <= 3
That is true.
It prints:
1
Then:
i++
changes i to 2.
Second Loop
JavaScript checks:
2 <= 3
That is true.
It prints:
2
Then i becomes 3.
Third Loop
JavaScript checks:
3 <= 3
That is true.
It prints:
3
Then i becomes 4.
Loop Ends
JavaScript checks:
4 <= 3
That is false.
The loop stops.
What Is the Loop Counter?
A variable such as:
i
is commonly used as a loop counter.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
i is only a common name.
You could use a clearer name when it helps:
for (let number = 1; number <= 5; number++) {
console.log(number);
}
For small loops, i is widely understood.
Why Do Many Loops Start at 0?
JavaScript arrays use zero-based indexing.
That means the first item has index:
0
Example:
const products = ["Laptop", "Phone", "Tablet"];
console.log(products[0]);
Output:
Laptop
This is why array loops often start with:
let i = 0
rather than:
let i = 1
You will learn arrays in detail in the JavaScript Arrays tutorial.
Loop Through an Array With for
Consider:
const products = ["Laptop", "Phone", "Tablet"];
You can loop through the array:
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
Output:
Laptop
Phone
Tablet
The condition:
i < products.length
keeps the loop inside the valid array indexes.
For three items:
products.length
is:
3
The valid indexes are:
0
1
2
Why Use < Instead of <= With Array Length?
This is correct:
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
This is usually wrong:
for (let i = 0; i <= products.length; i++) {
console.log(products[i]);
}
Why?
If the array length is 3, the final loop tries:
products[3]
But the last valid index is:
2
The result is:
undefined
This is a common beginner mistake.
Real Website Example: Product List
Suppose:
const products = [
"Laptop",
"Keyboard",
"Mouse",
"Monitor"
];
You can display every name:
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
Output:
Laptop
Keyboard
Mouse
Monitor
Later, you can use similar loops to create HTML elements for product cards.
Real Website Example: Calculate Cart Total
Suppose a cart contains prices:
const prices = [500, 1200, 300, 800];
Start the total at zero:
let total = 0;
Then loop through the prices:
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log(total);
Output:
2800
Each loop adds another price to total.
This combines JavaScript variables and JavaScript operators with loops.
Counting Backward With a for Loop
A for loop does not have to count upward.
Example:
for (let i = 5; i >= 1; i--) {
console.log(i);
}
Output:
5
4
3
2
1
Here:
i--
reduces the counter after each loop.
Increase by More Than One
You can change the counter by more than one.
Example:
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
Output:
0
2
4
6
8
10
This loop increases by two each time.
Real Example: Show Even Numbers
You can print even numbers directly:
for (let number = 2; number <= 10; number += 2) {
console.log(number);
}
Output:
2
4
6
8
10
Another approach uses the remainder operator:
for (let number = 1; number <= 10; number++) {
if (number % 2 === 0) {
console.log(number);
}
}
This also prints the even numbers.
If % is unfamiliar, review the JavaScript Operators lesson.
JavaScript while Loop
A while loop repeats code while a condition remains truthy.
Syntax:
while (condition) {
// repeated code
}
Example:
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
Output:
1
2
3
4
5
The loop continues as long as:
count <= 5
returns true.
How a while Loop Works
Start with:
let count = 1;
Then:
while (count <= 3) {
console.log(count);
count++;
}
JavaScript:
- Checks the condition.
- Runs the block when the condition passes.
- Updates
count. - Checks the condition again.
- Stops when the condition becomes false.
When to Use while
A while loop is useful when you do not know the exact number of repetitions before the loop starts.
For example, you may want to repeat until:
- A value reaches a limit
- A search finds a match
- A queue becomes empty
- A condition changes
- A retry count reaches a maximum
For a fixed number of repetitions, a for loop is often easier to read.
Real Website Example: Reduce Stock
Suppose stock needs to be processed until it reaches zero.
let stock = 3;
while (stock > 0) {
console.log(`Items left: ${stock}`);
stock--;
}
Output:
Items left: 3
Items left: 2
Items left: 1
When stock becomes 0, the condition fails and the loop stops.
JavaScript do...while Loop
A do...while loop runs the code once before checking the condition.
Syntax:
do {
// code
} while (condition);
Example:
let count = 1;
do {
console.log(count);
count++;
} while (count <= 3);
Output:
1
2
3
Difference Between while and do...while
A while loop checks first:
let count = 10;
while (count < 5) {
console.log(count);
}
Nothing runs because:
count < 5
is false immediately.
A do...while loop runs once first:
let count = 10;
do {
console.log(count);
} while (count < 5);
Output:
10
Even though the condition is false, the block runs once.
When to Use do...while
Use do...while when the code should run at least once before the condition is checked.
This pattern is less common than for or while in everyday frontend code, but it is still part of JavaScript and useful to understand.
JavaScript for...of Loop
The for...of loop is a simple way to loop through values in an array.
Example:
const products = ["Laptop", "Phone", "Tablet"];
for (const product of products) {
console.log(product);
}
Output:
Laptop
Phone
Tablet
This is often easier to read than a classic for loop when you only need each value.
for...of Syntax
The basic syntax is:
for (const item of collection) {
// use item
}
Example:
const cities = ["Delhi", "Noida", "Mumbai"];
for (const city of cities) {
console.log(city);
}
Output:
Delhi
Noida
Mumbai
Each loop places the next array value into:
city
When to Use for...of
Use for...of when:
- You need each array value
- You do not need the index
- You want simple readable code
For example:
const prices = [100, 200, 300];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total);
Output:
600
Getting the Index With for...of
If you need both the index and value, you can use:
const products = ["Laptop", "Phone", "Tablet"];
for (const [index, product] of products.entries()) {
console.log(index, product);
}
Output:
0 Laptop
1 Phone
2 Tablet
This syntax uses array methods and destructuring, which you will study later.
For beginners, a classic for loop is often simpler when the index is important.
for Loop vs for...of
Use a classic for loop when you need:
- The index
- Custom counting
- To skip by two or more positions
- To move backward
- More control over the loop counter
Use for...of when you mainly need each value.
Example with for:
for (let i = 0; i < products.length; i++) {
console.log(i, products[i]);
}
Example with for...of:
for (const product of products) {
console.log(product);
}
Choose the version that makes the code easier to understand.
What Is for...in?
JavaScript also has:
for...in
It loops through enumerable property keys.
Example:
const user = {
name: "Amit",
city: "Delhi"
};
for (const key in user) {
console.log(key);
}
Output:
name
city
You can access the values:
for (const key in user) {
console.log(user[key]);
}
Output:
Amit
Delhi
You will understand this better after the JavaScript Objects tutorial.
Do Not Use for...in as Your Normal Array Loop
Although for...in can produce array indexes, it is not the normal choice for looping through array values.
For arrays, prefer:
for
or:
for...of
depending on what you need.
Use for...in mainly when working with object property keys and when you understand its behavior.
JavaScript break Statement
break stops a loop immediately.
Example:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
Output:
1
2
3
4
When i becomes 5, JavaScript reaches:
break;
and exits the loop.
Real Website Example: Find a Product
Suppose:
const products = [
"Laptop",
"Phone",
"Keyboard",
"Monitor"
];
You can stop when the target is found:
for (const product of products) {
if (product === "Keyboard") {
console.log("Product found");
break;
}
}
Once the product is found, there is no need to continue checking the remaining items.
Later, you will learn array methods such as find() that are often better for this exact task.
JavaScript continue Statement
continue skips the rest of the current loop and moves to the next repetition.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
Output:
1
2
4
5
When i is 3, JavaScript skips:
console.log(i);
for that loop only.
The loop then continues with 4.
Real Website Example: Skip Out-of-Stock Products
Suppose:
const products = [
{ name: "Laptop", stock: 2 },
{ name: "Phone", stock: 0 },
{ name: "Mouse", stock: 5 }
];
You can skip unavailable products:
for (const product of products) {
if (product.stock === 0) {
continue;
}
console.log(product.name);
}
Output:
Laptop
Mouse
The phone is skipped because its stock is zero.
break vs continue
break stops the entire loop.
continue skips only the current repetition.
Example with break:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
Output:
1
2
Example with continue:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
Output:
1
2
4
5
Nested Loops
A loop can appear inside another loop.
This is called a nested loop.
Example:
for (let row = 1; row <= 2; row++) {
for (let column = 1; column <= 3; column++) {
console.log(`Row ${row}, Column ${column}`);
}
}
Output:
Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
For every outer loop, the inner loop runs completely.
Real Example: Product Variations
Suppose a product has colors and sizes:
const colors = ["Black", "White"];
const sizes = ["S", "M", "L"];
You can create every combination:
for (const color of colors) {
for (const size of sizes) {
console.log(`${color} - ${size}`);
}
}
Output:
Black - S
Black - M
Black - L
White - S
White - M
White - L
Nested loops are useful, but they can become expensive when both collections are very large.
What Is an Infinite Loop?
An infinite loop never reaches a stopping condition.
Example:
let count = 1;
while (count <= 5) {
console.log(count);
}
The problem is that:
count
never changes.
The condition:
count <= 5
remains true forever.
The correct version updates the variable:
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
Always make sure a while loop can eventually reach a false condition.
Infinite for Loop
This also creates an endless loop:
for (let i = 0; i < 5;) {
console.log(i);
}
i never increases.
Correct:
for (let i = 0; i < 5; i++) {
console.log(i);
}
When testing loops, be especially careful with the update step.
Loop Scope
Variables declared with let inside a loop are block scoped.
Example:
for (let i = 0; i < 3; i++) {
console.log(i);
}
After the loop:
console.log(i);
causes an error because i is not available outside that loop block.
This behavior helps keep loop counters from affecting unrelated code.
You learned basic scope in the JavaScript Variables tutorial.
Using const Inside a Loop
In a for...of loop, this is common:
const products = ["Laptop", "Phone"];
for (const product of products) {
console.log(product);
}
A new product binding is created for each loop iteration.
You are not reassigning the same const variable manually.
This is why const works well here.
Loop Through Strings
Strings are iterable, so for...of can loop through their characters.
Example:
const word = "Java";
for (const letter of word) {
console.log(letter);
}
Output:
J
a
v
a
This can be useful when processing text character by character.
Real Website Example: Render Menu Labels
Suppose:
const menuItems = [
"Home",
"Products",
"About",
"Contact"
];
You can loop through them:
for (const item of menuItems) {
console.log(item);
}
Later, when you learn the DOM, you can use a loop to create menu elements on the page.
See the JavaScript DOM Manipulation tutorial when you reach that part of the course.
Real Website Example: Count Completed Tasks
Suppose:
const tasks = [
{ title: "Design page", completed: true },
{ title: "Write content", completed: false },
{ title: "Test form", completed: true }
];
Count completed tasks:
let completedCount = 0;
for (const task of tasks) {
if (task.completed) {
completedCount++;
}
}
console.log(completedCount);
Output:
2
This combines loops, objects, booleans, and if statements.
Real Website Example: Find Highest Price
Suppose:
const prices = [500, 1200, 750, 2000, 300];
Start with the first price:
let highestPrice = prices[0];
Then compare every price:
for (const price of prices) {
if (price > highestPrice) {
highestPrice = price;
}
}
console.log(highestPrice);
Output:
2000
This is a useful example of loops and comparisons working together.
Real Website Example: Build a Total From Cart Items
Suppose each cart item has a price and quantity:
const cart = [
{ price: 500, quantity: 2 },
{ price: 1000, quantity: 1 },
{ price: 250, quantity: 3 }
];
Calculate the total:
let total = 0;
for (const item of cart) {
total += item.price * item.quantity;
}
console.log(total);
Output:
2750
Each loop calculates one line total and adds it to the cart total.
Real Website Example: Stop After First Match
Suppose:
const users = [
"Amit",
"Riya",
"Kabir",
"Sara"
];
Find "Kabir":
for (const user of users) {
if (user === "Kabir") {
console.log("User found");
break;
}
}
The loop stops as soon as the match is found.
Choosing the Right Loop
A simple beginner guide is:
Use for when:
- You know the number of repetitions
- You need an index
- You need custom counter control
- You need to count forward or backward
Example:
for (let i = 0; i < 5; i++) {
// ...
}
Use while when:
- Repetition depends on a condition
- The number of loops is not known in advance
Example:
while (stock > 0) {
// ...
}
Use do...while when:
- The block must run at least once
Example:
do {
// ...
} while (condition);
Use for...of when:
- You want each value from an array or iterable
- You do not need manual index control
Example:
for (const product of products) {
// ...
}
Loops vs Array Methods
Later, you will learn array methods such as:
forEach()
map()
filter()
find()
reduce()
These methods can replace some loop patterns.
For example, this loop:
for (const product of products) {
console.log(product);
}
can sometimes be written with:
products.forEach((product) => {
console.log(product);
});
Do not rush into array methods yet.
Understanding normal loops first makes methods such as map(), filter(), and reduce() much easier to learn later.
Common Beginner Mistakes
Forgetting to Update the Counter
Wrong:
let count = 1;
while (count <= 5) {
console.log(count);
}
The condition never changes.
Add:
count++;
Using <= With Array Length
Wrong:
for (let i = 0; i <= products.length; i++) {
console.log(products[i]);
}
Use:
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
Array indexes stop one number before the array length.
Starting at the Wrong Index
If you start:
let i = 1
you skip the first array item.
For normal array indexing, start at:
0
Using the Wrong Update Direction
This loop never finishes:
for (let i = 1; i <= 5; i--) {
console.log(i);
}
i keeps getting smaller, so:
i <= 5
remains true.
To count upward, use:
i++
Changing the Wrong Variable
Consider:
let count = 1;
let total = 0;
while (count <= 5) {
total++;
}
count never changes, so the loop does not stop.
Make sure the variable controlling the condition is updated.
Using for...in for Normal Array Values
Avoid:
for (const item in products) {
console.log(item);
}
This gives property keys or indexes, not the values you probably expect.
For values, use:
for (const item of products) {
console.log(item);
}
Forgetting break Stops the Entire Loop
Once JavaScript reaches:
break;
the loop ends immediately.
Use continue when you only want to skip one iteration.
Putting continue Before Important Code
Example:
for (let i = 1; i <= 5; i++) {
continue;
console.log(i);
}
The console.log() is never reached.
Code after continue in that iteration is skipped.
Creating Deeply Nested Loops Without Need
Nested loops can become difficult to read and can perform many operations.
If both loops contain 1,000 items, the inner code may run around one million times.
Use nested loops only when the task actually requires combinations or repeated inner processing.
Modifying an Array Carelessly While Looping
Removing or inserting items while using index-based loops can change array positions.
That can cause skipped or repeated items.
When you later learn array methods, you will see safer patterns for many transformation tasks.
Best Practices for JavaScript Loops
Choose the loop that makes your intention clear.
Use for...of when you only need array values.
Use a classic for loop when you need index control.
Keep loop conditions simple.
Make sure while and do...while loops can eventually stop.
Use descriptive names when i would make the code unclear.
Prefer:
for (const product of products) {
console.log(product);
}
over vague names such as:
for (const x of products) {
console.log(x);
}
Use break when continuing the loop no longer has value.
Use continue when only one iteration should be skipped.
Avoid changing unrelated variables inside a loop.
Break complicated loop logic into functions after you learn JavaScript Functions.
Beginner Exercise
Write a for loop that prints the numbers:
1
2
3
4
5
Then change it to print:
5
4
3
2
1
Next, create:
const colors = ["Red", "Green", "Blue"];
Use for...of to print every color.
Challenge Exercise
Create:
const prices = [500, 1200, 300, 700];
Use a loop to calculate the total price.
Your result should be:
2700
Then count how many prices are greater than ₹500.
The result should be:
2
Extra Challenge
Create:
const products = [
{ name: "Laptop", stock: 3 },
{ name: "Phone", stock: 0 },
{ name: "Keyboard", stock: 5 },
{ name: "Mouse", stock: 0 }
];
Loop through the products.
Skip products with zero stock using:
continue;
Print only:
Laptop
Keyboard
Frequently Asked Questions
What is a loop in JavaScript?
A loop repeats a block of code while a condition or collection requires more repetitions.
What are the main loops in JavaScript?
The main beginner loops are for, while, do...while, and for...of.
JavaScript also provides for...in for property keys.
How does a for loop work?
A for loop usually contains an initial value, a condition, and an update.
for (let i = 0; i < 5; i++) {
console.log(i);
}
What is a while loop?
A while loop repeats code while its condition remains truthy.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
What is a do...while loop?
A do...while loop runs its block once before checking the condition.
This means the block always runs at least one time.
What is a for...of loop?
for...of loops through values from arrays and other iterable values.
for (const product of products) {
console.log(product);
}
What is the difference between for and for...of?
A classic for loop gives you direct control over the counter and index.
for...of gives you each value directly and is often easier when you do not need the index.
What is the difference between for...in and for...of?
for...in loops through property keys.
for...of loops through iterable values.
For normal array values, for...of is usually the better choice.
What does break do in a JavaScript loop?
break stops the entire loop immediately.
What does continue do in a JavaScript loop?
continue skips the rest of the current iteration and moves to the next one.
What is an infinite loop?
An infinite loop never reaches a stopping condition.
This often happens when the loop's control variable is not updated correctly.
Why do JavaScript array loops often start at 0?
JavaScript arrays use zero-based indexes. The first array item has index 0.
Why do we use i < array.length?
If an array has a length of 3, its valid indexes are 0, 1, and 2.
Using < stops before index 3, which does not exist.
Can I use if statements inside loops?
Yes.
Conditions inside loops are very common.
for (const price of prices) {
if (price > 500) {
console.log(price);
}
}
Can loops be nested?
Yes.
A loop inside another loop is called a nested loop.
Use nesting only when the task requires it because repeated inner loops can perform many operations.
Should I use loops or array methods?
Learn normal loops first.
Later, array methods such as forEach(), map(), filter(), find(), and reduce() can make many array tasks easier to express.
What should I learn after JavaScript loops?
Learn JavaScript functions next. Functions let you group reusable code and make loops, conditions, and other logic easier to organize.
Summary
JavaScript loops repeat code.
The main loops you learned are:
for
while
do...while
for...of
Use a for loop when you need counter or index control.
Use while when repetition depends mainly on a condition.
Use do...while when the code must run at least once.
Use for...of when you want each value from an array or another iterable.
You also learned:
- How array indexes work
- Why array loops often start at
0 - How to calculate totals with loops
- How
breakstops a loop - How
continueskips one iteration - How nested loops work
- How infinite loops happen
- Why
for...inandfor...ofare different - How loops work with conditions and arrays
Loops are essential for processing repeated data in real websites.
Continue Learning JavaScript
Previous Lesson: JavaScript if else Explained
Course Home: JavaScript Tutorial for Beginners
Next Lesson: JavaScript Functions Explained for Beginners
In the next lesson, you will learn how to create reusable JavaScript functions, pass values with parameters, return results, and organize repeated logic more clearly.
