Loops let JavaScript execute a block of code repeatedly. They are one of the most basic tools for data processing, iteration, and algorithm implementation.
A loop repeats a task until a condition is no longer satisfied.
JavaScript provides several loop forms:
forwhiledo...whilefor...infor...offorfor (let i = 0; i < 5; i++) { console.log(i);}const arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) { console.log(arr[i]);}for (let i = 0; i < 3; i++) { for (let j = 0; j < 2; j++) { console.log(i, j); }}whilelet i = 0;
while (i < 5) { console.log(i); i++;}while is useful when the number of iterations is not known in advance.
let password = "";
while (password !== "123456") { password = "123456";}do...whilelet i = 0;
do { console.log(i); i++;} while (i < 5);do...while always runs the body at least once.
for...inconst user = { name: "Tom", age: 20 };
for (const key in user) { console.log(key, user[key]);}for...in iterates over enumerable property keys, not values.
It is mainly for objects, not arrays.
for...ofconst arr = ["a", "b", "c"];
for (const item of arr) { console.log(item);}for...of is usually cleaner than index-based loops when you only need values.
breakStops the loop completely.
for (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i);}continueSkips the current iteration and moves to the next one.
for (let i = 0; i < 5; i++) { if (i === 2) continue; console.log(i);}for: index-based controlwhile: unknown number of iterationsdo...while: must run at least oncefor...in: object keysfor...of: iterable valuesPerformance differences usually matter less than readability unless you are in a true hot path.
const scores = [90, 85, 100];let total = 0;
for (const score of scores) { total += score;}const items = document.querySelectorAll("li");
for (const item of items) { item.classList.add("active");}Loops are the basis of searching, sorting, counting, traversal, and more.
Always make sure the loop condition can eventually become false.
for...inDo not use it as your default loop for arrays.
Be careful with asynchronous logic in loops.
for (const id of ids) { const user = await fetchUser(id); console.log(user);}Sequential await is sometimes correct, but sometimes you may want Promise.all.
Modern JavaScript often uses:
mapfilterreducesomeeveryThese are often more declarative than manual loops.
for...of with await for sequential async workPromise.all for concurrent async workLoops are fundamental, but choosing the right loop matters: