본문으로 건너뛰기

For Loops

For Loop

The for loop is the most basic loop in JavaScript, used to repeatedly execute a block of code as long as a given condition is true.


Basic Structure of a for Loop

for (initialization; condition; update) {
// Code to be executed repeatedly
}
  • Initialization: An expression that is executed once at the beginning of the loop. It is usually used to initialize a variable for the loop.

  • Condition: This condition is checked before each iteration, and if it is true, the code block continues to execute; if false, the loop stops.

  • Update: An expression that is executed after each iteration of the code block. It is usually used to increment the loop variable.

Using a for loop is like setting an alarm on a clock. When you set the alarm (initialization), and the specified time arrives (condition check), the alarm sounds. Then, it waits until the specified time comes around again (update). Similarly, a for loop repeats the code until the specified condition is satisfied.


Examples of a for Loop

  1. Printing numbers from 0 to 4:
for (let i = 0; i < 5; i++) {
console.log(i); // Prints 0, 1, 2, 3, 4 in sequence.
}

  1. Printing all elements in an array:
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // Prints "apple", "banana", "cherry" in sequence.
}

  1. Counting down from 5 to 1:
for (let i = 5; i > 0; i--) {
console.log(i); // Prints 5, 4, 3, 2, 1 in sequence.
}