Back to course

Introduction to Looping: Why We Need Repetition

JavaScript: The Complete '0 to Hero' Beginner Course

37. Introduction to Looping

Loops are fundamental to programming. They allow you to execute a block of code repeatedly until a specific condition is met. This avoids writing repetitive code (following the DRY—Don't Repeat Yourself—principle).

Core Components of a Loop

Most traditional loops require three parts:

  1. Initialization: Setting up a counter variable (e.g., let i = 0).
  2. Condition: The test that determines if the loop continues (e.g., i < 10). If the condition is false, the loop stops.
  3. Iteration/Update: Modifying the counter variable so that the loop eventually terminates (e.g., i++).

The for Loop (The Workhorse)

The for loop is the most common type and combines all three components into a concise structure.

javascript for (let i = 0; i < 5; i++) { console.log('Iteration number: ' + i); }

// Output: 0, 1, 2, 3, 4

We will now look at for, while, and do...while in detail.