← 講座に戻る: JavaScript from scratch

for and while loops

動画は近日公開

A loop repeats a block of code while a condition is met. Imagine you want to print the numbers from 1 to 1000: writing a thousand console.log calls would be absurd. Loops are the tool to automate repetitive tasks, walk through lists of data and repeat an action until something happens. JavaScript offers several kinds; today we study for, while and do...while.

The for loop

The for loop has three parts in parentheses, separated by semicolons: the initialization (runs once, usually let i = 0), the condition (checked before each turn) and the update (runs at the end of each turn, usually i++). It is ideal when you know how many times you want to repeat. Declare the counter with let, not const, because it changes on every turn.

javascript
for (let i = 1; i <= 5; i++) {
  console.log('Turn', i);
}

// Sum of numbers from 1 to 100
let total = 0;
for (let n = 1; n <= 100; n++) {
  total += n;
}
console.log(total); // 5050

// Counting down by 2
for (let i = 10; i >= 0; i -= 2) {
  console.log(i); // 10, 8, 6, 4, 2, 0
}

while and do...while

The while loop checks the condition before each turn and is used when you do not know in advance how many repetitions there will be, for example while a value has not reached a limit. do...while runs the block at least once and checks the condition at the end. The danger of while is the infinite loop: if nothing inside the block changes the condition, the program never ends. If it happens in Node, stop it with Ctrl + C.

javascript
// How many times can we double 1 before passing 1000?
let value = 1;
let steps = 0;
while (value <= 1000) {
  value *= 2;
  steps++;
}
console.log(steps, value); // 10 1024

let tries = 0;
do {
  tries++;
  console.log('Attempt', tries);
} while (tries < 3);

break and continue

Inside a loop you can use break to exit immediately and continue to jump to the next turn without running the rest of the block. They are useful to find the first element that meets something or to ignore cases that do not matter. Do not overuse them: if your loop has many break and continue statements, perhaps the logic should be reorganized.

javascript
// Print only the odd numbers up to 9, stop when reaching 7
for (let i = 1; i <= 9; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  if (i === 7) break;        // leave the loop
  console.log(i);            // 1, 3, 5
}

Nested loops

A loop can contain another loop. The inner one runs completely for each turn of the outer one, so with 3 outer turns and 4 inner ones the inner code runs 12 times. Nested loops are used for tables, grids and combinations, such as a multiplication table. Use them with care: as the numbers grow, the number of operations multiplies and the program becomes slow. Use different names for the counters (i, j) and avoid more than two or three levels; if the code gets complicated, extract the inner loop into a function with a descriptive name.

javascript
// Multiplication table 1..3
for (let i = 1; i <= 3; i++) {
  let row = '';
  for (let j = 1; j <= 4; j++) {
    row += `${i * j}\t`;
  }
  console.log(row);
}
// 1  2  3  4
// 2  4  6  8
// 3  6  9  12

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →