Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Mastering the for Loop in JavaScript | Looping Through Data in JavaScript
Introduction to JavaScript

bookMastering the for Loop in JavaScript

メニューを表示するにはスワイプしてください

The for loop is a common way to repeat code. It uses three parts inside the parentheses:

for (Initialization; Condition; Increment/Decrement) {
  // code block
}

What each part means:

  • Initialization: creates the loop counter (runs once);
  • Condition: checked before every iteration;
  • Increment/Decrement: updates the counter after each loop.
Note
Note

An iteration is one full execution of the loop body.

123
for (let i = 1; i < 5; i++) { console.log("Loop iteration:", i); };
copy
  • let i = 1: initialization;
  • i < 5: condition;
  • i++: increment;
  • console.log(...): loop body.

This repeats until the condition becomes false.

You can also use decrement in the for loop, as shown here:

123
for (let i = 15; i > 10; i--) { console.log("i =", i); }
copy

The for loop counter is unique to its scope, so you don't need to worry about the counter name conflicting with other variables:

12345678
let i = 2077; console.log("(global) i =", i); for (let i = 0; i < 4; i++) { console.log("(for) i =", i); } console.log("(global) i =", i);
copy

Different expressions for Increment/Decrement operations can be used as well:

123
for (let i = 0; i < 40; i += 7) { console.log("i =", i); };
copy

Comparing the for and while loops

When comparing for and while loops, the for loop is often simpler and more concise. Here's an example of equivalent loops:

1234567891011
// `while` let a = 1; while (a <= 3) { console.log("While:", a); a++; } // `for` for (let i = 1; i <= 3; i++) { console.log("For:", i); }
copy

The for loop is usually shorter and keeps the counter inside its own scope.

question mark

You want to print every Summer Olympics year from 2000 to 2016, inclusive. What should go in the loop condition?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  3
some-alt