xSKILLby Infirals
Register

JavaScript for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Loops and iteration

Control flow and functions15 min readLesson 2 of 4

2.1 Repeating work

A loop runs a block until a condition stops it. The block is the loop body, the condition is evaluated before or after each pass, and the loop variable tracks progress. Every loop needs a way to end: a counter that changes, a collection that is consumed, or a condition that eventually becomes false.

The most common loop is a counting for loop. It packs the start, the condition and the update into one line, and each part is visible at the top of the block. A reader can predict the number of passes without tracing assignments scattered through the body.

javascript
let total = 0;

for (let number = 1; number <= 5; number += 1) {
  total += number;
}

console.log(total);

Output

15

The loop variable number belongs to the loop block, so it disappears after the loop ends. Declaring a fresh binding on every pass also makes closures inside the loop capture the right value, which is the behaviour you want when the loop creates callbacks or timers.

Choose a name that describes the current item. user, row or character gives the body meaning, while i is fine for a numeric index when the body is two lines long and the index is the only thing the loop asks about.

2.2 while and do while

A while loop checks its condition before every pass. It is the right tool when the number of passes is unknown, such as reading items until one matches. The loop body must change something that the condition checks, or the loop never ends.

A do while loop checks after the body, so it always runs at least once. That shape fits a retry or a menu, where the first action happens before the stopping question. In most code, while is clearer because the condition appears at the top.

javascript
let countdown = 3;

while (countdown > 0) {
  console.log(countdown);
  countdown -= 1;
}

console.log("Lift off");

Output

3
2
1
Lift off

2.3 for of

for of visits the values of an iterable: an array, a string, a Set, a Map or any object with an iterator. It removes the index bookkeeping and reads as "for each value". Use it when the value matters more than the position.

for in is different. It visits enumerable property names of an object, including inherited ones, and its order is not guaranteed for arbitrary keys. For arrays, for in returns index strings, which is rarely what a beginner expects. Reach for for of on arrays and Object.keys when you need object properties.

javascript
const names = ["Aarav", "Meera", "Sana"];

for (const name of names) {
  console.log(name.toUpperCase());
}

for (const character of "Hi") {
  console.log(character);
}

Output

AARAV
MEERA
SANA
H
i

2.4 break and continue

break leaves the loop immediately. continue skips the rest of the current pass and moves to the next one. They are useful for searching and filtering, and both can make a loop harder to follow when used in several places.

Prefer a condition at the top when the loop can decide before running the body. Break is for early success or a hard stop, such as finding one item and stopping the search. Continue is for skipping invalid items without wrapping the whole body in an if block.

javascript
const numbers = [4, 7, 10, 13, 16];
let firstOdd = null;

for (const number of numbers) {
  if (number % 2 === 0) continue;
  firstOdd = number;
  break;
}

console.log(firstOdd);

Output

7

2.5 Nested loops

A loop inside a loop runs the inner loop once for each outer pass. The total passes multiply, so two loops over n items perform n squared passes. That is fine for small patterns and expensive for large data, which is why nested loops deserve a second look when one list is searched inside another.

The classic optimisation is to build a lookup object before the loops. One pass creates a Map from key to item, and the second pass reads it in constant time. That turns an n times m search into n plus m work, a habit module 3 revisits with array methods.

javascript
for (let row = 1; row <= 3; row += 1) {
  let line = "";
  for (let column = 1; column <= 3; column += 1) {
    line += row * column + " ";
  }
  console.log(line.trim());
}

Output

1 2 3
2 4 6
3 6 9

2.6 Loop costs and safety

Each pass does the work in the body, so the cost grows with the number of passes. A loop that searches an array for every user in another array is quadratic. A loop that reads a property of the current item is linear and cheap.

Infinite loops happen when the condition never becomes false: a counter that is not updated, a condition that compares the wrong variable, or a while(true) with no break. When a script freezes the page, the first suspect is a loop. Add a maximum counter while debugging and log the state at the top of the body when the exit condition is unclear.

2.7 Choosing the right loop

NeedLoop
a known number of passesfor
repeat until a condition changeswhile
run at least once before checkingdo while
visit every value of an array or stringfor of
visit property names of an objectObject.keys with for of

The table is a starting point, not a rule. A for loop with a break can behave like a while loop, and a while loop can count passes. Choose the shape that makes the stopping condition obvious to the next reader.

When both shapes are equally clear, prefer for of for collections. It removes the index variable and the length check, which are two places to make an off-by-one mistake.

2.8 Accumulators

Many loops build a result while they iterate: a running sum, a joined string, a filtered array or a count. Start with an empty value before the loop, update it inside the body, and use it after the loop. The pattern is called an accumulator.

Keep the initial value explicit. let total = 0 states that the loop adds numbers, while let total leaves undefined and turns the first += into NaN. For strings, start with ""; for arrays, start with []. The accumulator's type should match the type the loop adds.

The example below counts words by length in a small array. The object starts empty, the loop adds or increments a key, and the final log shows the shape of the result.

javascript
const words = ["pen", "book", "bag", "note"];
const byLength = {};

for (const word of words) {
  const length = word.length;
  byLength[length] = (byLength[length] || 0) + 1;
}

console.log(JSON.stringify(byLength));

Output

{"3":2,"4":2}

2.9 Loop variable scope and closures

A let loop variable is fresh on each pass, so a callback created inside the pass captures that pass's value. A var loop variable is shared across passes, so every callback captures the final value. This difference explains many old interview outputs and is one more reason to declare loop counters with let.

The same rule applies to array methods. A callback receives the current item as a parameter, so it does not need the shared loop variable at all. Prefer the callback parameter, and the closure problem disappears.

2.10 Common mistakes

  • Forgetting to update the loop variable inside a while loop.
  • Using <= with an array length and reading one element past the end.
  • Mixing up for of and for in on an array.
  • Changing an array's length while looping over it.
  • Using break in the wrong loop when loops are nested.
  • Building strings with += in a very large loop instead of joining an array.

Exam

Trace loop questions with a table: one column for each variable, one row per pass. Stop when the condition fails, then count the printed lines. Most errors come from the first and last pass, not the middle.

  • Write a for loop that prints the numbers 1 to 10.
  • Rewrite a counting loop as a while loop and check the same output.
  • Use for of to sum an array of prices.
  • Build a loop with break and explain what stops it.