HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaScriptVariables (let / const)Data TypesOperatorsStringsArraysObjectsConditions (if / else)Loops (for / while)FunctionsArrow Functions (=>)Array Methods (map / filter / reduce)
REFERENCE
📖 Overview
🖥️ Output & Console
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Object
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
JavaScript›Loops (for / while)

Loops (for / while)

for for fixed repetition, for...of for traversing arrays, while for conditional repetition.

Simple enough for a 5-year-old to understand

for loop

Three parts: initialization, condition, increment. Used for a specific number of repetitions.

Example code
1
for (let i = 1; i <= 3; i++) {
Start from i=1, up to 3, +1 on each turn.
LoopStart from i=1, up to 3, +1 on each turn.
2
console.log(i);
Prints 1, 2, 3.
Output / InputPrints 1, 2, 3.
3
}
End of loop.
LoopEnd of loop.
LoopOutput / Input
💡 Hint: i++ means "increment i by 1" (same as i = i + 1).

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

A loop is a way to repeat the same task, and JavaScript has multiple forms for this. The classic for loop works with a counter; for-of iterates directly over elements; while runs as long as a condition is met. Additionally, array methods like forEach, map, and filter do the same job without needing to write a loop.

Which method you choose in modern JavaScript depends on the task at hand. If you want to transform every element and get a new array, use map; if you want to filter them, use filter; if you just want to perform an operation, use for-of. The classic for loop is useful when you need an index or need to break out of the loop early.

What you will learn

  • The classic for loop and counter logic
  • Iterating over elements with for-of
  • The difference between while and do-while
  • Using break and continue
  • Building loop-free solutions with forEach, map, and filter
  • Why using for-in is not recommended for arrays

When to use?

To display a list on the screen use map, to filter use filter, and to calculate a total use reduce. If you need to exit a loop early, you need for or for-of, because break does not work inside forEach.

For tasks where the end count is uncertain—like trying until a condition is met—use while; in this case, make sure the loop has a way out.

Common mistakes

Wrong

const items = [1, 2, 3];
items.forEach((n) => {
  if (n === 2) break;
});

Break cannot be used inside forEach; you get a "SyntaxError: Illegal break statement". forEach always visits every element. If early exit is required, for-of or the some method should be used.

Correct

const items = [1, 2, 3];
for (const n of items) {
  if (n === 2) break;
}

Wrong

const nums = [1, 2, 3];
for (const i in nums) {
  console.log(i + 1);
}

for-in gives INDICES in an array, and these indices are STRINGS. Therefore, the operation i + 1 performs concatenation and prints "01", "11", "21". For arrays, you should use for-of.

Correct

const nums = [1, 2, 3];
for (const n of nums) {
  console.log(n + 1);
}

Wrong

let i = 0;
while (i < 5) {
  console.log(i);
}

Since the counter never increases, the condition always remains true and the loop enters an infinite state; the browser tab freezes. When using while, it is mandatory to ensure there is a change affecting the condition inside the loop.

Correct

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

Frequently asked questions

What is the difference between map and forEach?

map collects the returned value for each element and returns a NEW array; forEach returns nothing, it only applies the operation. If you are doing a transformation, use map; if you are producing a side effect, use forEach. Assigning the result of forEach to a variable is meaningless, it yields undefined.

What is the difference between for-of and for-in?

for-of iterates over VALUES and is the right choice for arrays. for-in iterates over KEYS and is designed for objects. Using for-in on arrays both gives string indices and does not guarantee order.

I entered an infinite loop and the browser froze, what should I do?

You need to close the tab; because JavaScript runs on a single thread, an infinite loop freezes the entire page. Then check your loop condition and make sure the counter actually changes. Using for instead of while during development reduces this risk.

Summary

In JavaScript, map is used for transformation, filter for filtering, and for-of for traversal requiring early exit. Two classic pitfalls: break not working inside forEach, and for-in returning string indices on an array.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code