Loops in JavaScript
By Syncfusion®, Inc. · Last updated
Repeating work with for, while and do...while, walking objects with for...in and arrays with for...of, and controlling a loop with break and continue.
What Is a Loop?
Loop = code that repeats while a condition stays true.
- Print 5 ticket numbers without writing 5 lines.
- Add up every price in a cart.
- Stop as soon as you find what you want.
Simple lesson: write the work once, and the loop repeats it for each item.
A Real-World Example
A cart has 3 items: ₹120, ₹80 and ₹45. A loop visits each price and adds it to a total. With 300 items, the same 3 lines of code still work.
₹120
₹80
₹45
total ₹120 ₹200 ₹245 One pass of the loop for each price.
Each pass visits one item and updates the total.
A loop that never stops is stopped by the box after a few seconds, so you can try things safely.
What You Will Learn
for,whileanddo...whileloops.for...infor the keys of an object.for...offor the values of an array or string.breakandcontinue.
For Loop
Use for when you know how many times to repeat.
for (start; condition; step): start once, check before each pass, step after each pass.
Printing five ticket numbers with one for loop
for (let i = 1; i <= 5; i++) {
console.log("Ticket", i);
}
Expected output:
Ticket 1
Ticket 2
Ticket 3
Ticket 4
Ticket 5
The counter is often an index into an array. Stop at i < cart.length:
Using the counter as an index into an array
const cart = ["Pen", "Notebook", "Lunch box"];
for (let i = 0; i < cart.length; i++) {
console.log(i + 1 + ".", cart[i]);
}
Expected output:
1. Pen
2. Notebook
3. Lunch box
While Loop
Use while when you do not know how many passes you need. It checks the condition before each pass.
Saving 150 each month until the savings reach 1000
let savings = 0;
let months = 0;
while (savings < 1000) {
savings += 150;
months++;
}
console.log(months, "months, saved", savings);
Expected output:
7 months, saved 1050
Something inside must change the condition, or the loop never ends:
// Not runnable, on purpose: savings never changes,
// so savings < 1000 is true forever.
let savings = 0;
while (savings < 1000) {
console.log("Still saving...");
}
Do While Loop
do...while runs the block first, then checks. So it always runs at least once.
The same false condition in while and do...while
let stock = 0;
while (stock > 0) {
console.log("while: selling one");
}
do {
console.log("do...while: ran once anyway");
} while (stock > 0);
Expected output:
do...while: ran once anyway
For In Loop
for...in gives the keys of an object. Read the value with object[key].
Listing every key and value of one customer object
const customer = { name: "Asha", city: "Pune", orders: 3 };
for (const key in customer) {
console.log(key, "=", customer[key]);
}
Expected output:
name = Asha
city = Pune
orders = 3
for...in also visits inherited keys. To get only the object's own keys, use for (const key of Object.keys(obj)).
On an array, for...in gives index strings. Use for...of for arrays instead.
for...in on an array gives the index as a string
const sizes = ["S", "M"];
for (const i in sizes) {
console.log(i, typeof i);
}
Expected output:
0 string
1 string
For Of Loop
for...of gives each value directly. No index to manage.
Adding up a cart with for...of
const prices = [120, 80, 45];
let total = 0;
for (const price of prices) {
total += price;
}
console.log("Total:", total);
Expected output:
Total: 245
It works on strings too, one character at a time:
for...of over a string gives one character at a time
for (const letter of "SALE") {
console.log(letter);
}
Expected output:
S
A
L
E
Break Statement
break leaves the whole loop at once.
Stopping at the first order over 500
const totals = [250, 180, 640, 900];
for (const total of totals) {
if (total > 500) {
console.log("First big order:", total);
break;
}
console.log("Checked", total);
}
Expected output:
Checked 250
Checked 180
First big order: 640
Continue Statement
continue skips the rest of this pass and moves to the next one.
Skipping the items that are out of stock
const items = [
{ name: "Pen", stock: 10 },
{ name: "Bag", stock: 0 },
{ name: "Mug", stock: 4 },
];
for (const item of items) {
if (item.stock === 0) continue;
console.log("Show", item.name);
}
Expected output:
Show Pen
Show Mug
Loops on a Web Page
Build one <li> per product with for...of. Skip sold-out items with continue, and count the rest.
Drawing a product list with a loop
const products = [
{ name: "Steel bottle", price: 299, stock: 8 },
{ name: "Lunch box", price: 349, stock: 0 },
{ name: "Notebook", price: 60, stock: 25 },
{ name: "Pencil box", price: 120, stock: 3 },
];
const list = document.querySelector("#products");
let shown = 0;
for (const product of products) {
if (product.stock === 0) continue;
const li = document.createElement("li");
li.textContent = `${product.name} — ₹${product.price}`;
list.append(li);
shown++;
}
document.querySelector("#status").textContent = `${shown} of ${products.length} products in stock`;
console.log("rows drawn:", shown);
Add a fifth product to the array and run again. The page grows with no new loop code.
Easy way to remember: for**...of** = values of a list. for**...in** = keys in an object.
TL;DR
forwhen you know the count;whilewhen you do not.do...whilealways runs at least once.for...ofgives values;for...ingives keys.breakleaves the loop;continueskips one pass.- Always change something that ends the loop.
Try this
In the first for loop, change i <= 5 to i < 5. Now you get only 4 tickets. Off-by-one mistakes hide in that one character.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
i <= cart.length | The last index is the length | The last index is length - 1 | An extra undefined pass |
Not changing the while variable | The loop ends by itself | Something must make the condition false | The loop never stops |
for...in on an array | It gives values | It gives index strings | "0", "1" instead of items |
for...of on a plain object | Objects are lists | Plain objects are not iterable | TypeError: customer is not iterable |
continue when you meant break | Both stop the loop | continue skips one pass only | The loop keeps going |
Quick reference
| Syntax | Meaning |
|---|---|
for (let i = 0; i < n; i++) { ... } | repeat n times with a counter: start, check, update |
while (condition) { ... } | check first, then repeat while the condition is true |
do { ... } while (condition); | run once, then repeat while the condition is true |
for (const key in object) { ... } | walk through the keys of an object |
for (const value of array) { ... } | walk through the values of an array or string |
break; | leave the loop straight away |
continue; | skip the rest of this pass and go to the next one |
Exercises
What to Remember
- A loop repeats work for each item.
- Pick the loop by what you know: a count, a condition, or a list.
breakandcontinuecontrol the flow inside.
Next: Function Basics. Give a piece of code a name, and reuse it.