← Back to Chapters

JavaScript Loops

? JavaScript Loops

? Quick Overview

Loops in JavaScript let you repeat a block of code multiple times. They are essential for tasks like processing arrays, iterating over object properties, repeating an action until a condition is met, and working with user input or runtime data.

Common loop types include for, for...in, for...of, while, and do...while. Each loop has a slightly different use case, but all revolve around three main ideas: start, condition, and update.

? Key Concepts

  • Iteration: One complete execution of the loop body.
  • Loop control variable: A variable (like i or count) that changes on each iteration.
  • for loop: Best when you know in advance how many times to repeat a task.
  • for...in: Iterates over keys (enumerable properties) of an object.
  • for...of: Iterates over values of an iterable (arrays, strings, Maps, Sets, etc.).
  • while: Repeats as long as a condition stays true (condition is checked before each run).
  • do...while: Similar to while, but runs the body at least once before checking the condition.
  • Infinite loops: Happen when the condition never becomes false (often due to a missing or incorrect update).

? Syntax & Theory

Most loops follow the same logical pattern:

  • Initialization: Set a starting value (e.g., let i = 0;).
  • Condition: Decide when to stop (e.g., i < 5).
  • Update: Change the loop variable each time (e.g., i++).

For for loops, all three parts live in the loop header. In while and do...while, you typically put initialization before the loop, the condition in the loop header, and the update inside the loop body.

Objects and arrays are treated differently:

  • for...in is designed for objects and gives you property names (keys).
  • for...of is designed for iterables and gives you the values directly.

? Code Examples

? for Loop

The for loop is used when you know in advance how many times you want to execute a block of code. It has three parts inside the parentheses: initialization, condition, and increment/decrement.

? View for Loop Examples
// Classic for loop with a counter
for (let i = 0; i < 5; i++) {
  console.log("Iteration number:", i);
}

// Looping through an array using a for loop
const fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

? for...in Loop

The for...in loop iterates over enumerable properties (keys) of an object. It is useful when working with objects to access keys and their values.

? View for...in Example
const person = {name: "Alice", age: 30, city: "NY"};
for (let key in person) {
  console.log(key + ": " + person[key]);
}

Note: Avoid using for...in on arrays if you want numeric indices, as it iterates over keys which can include inherited properties.

? for...of Loop

The for...of loop iterates over iterable objects such as arrays, strings, Maps, Sets, etc., giving you values directly.

? View for...of Examples
const colors = ["red", "green", "blue"];
for (let color of colors) {
  console.log(color);
}

// Using for...of with a string
const message = "Hello";
for (let char of message) {
  console.log(char);
}

⏳ while Loop

The while loop runs as long as a specified condition is true. It checks the condition before each iteration, so if the condition is initially false, the loop body will never run.

? View while Loop Example
let count = 0;
while (count < 3) {
  console.log("Count is:", count);
  count++;
}

Use case: Waiting for a certain condition that depends on runtime values.

? do...while Loop

The do...while loop guarantees the loop body executes at least once before the condition is tested. This is useful when the loop code must run initially regardless of the condition.

? View do...while Examples
let number = 0;
do {
  console.log("Number is:", number);
  number++;
} while (number < 3);

// Runs once even though the condition is false
let n = 5;
do {
  console.log("Runs once even though condition is false");
} while (n < 3);

➕ Sum of Numbers Using for Loop

? View Sum Example
let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log("Sum of numbers from 1 to 5 is:", sum);

? Looping Over Object Properties and Arrays

Using for...in for object properties and for...of for array values:

? View Object and Array Loop Examples
// Iterating over an object
const book = {title: "1984", author: "Orwell"};
for (let prop in book) {
  console.log(`${prop}: ${book[prop]}`);
}

// Iterating over an array
const numbers = [10, 20, 30];
for (const num of numbers) {
  console.log(num);
}

? Live Output & Explanation

?️ What the Console Prints

  • For the classic for loop:
    Iteration number: 0
    Iteration number: 1
    Iteration number: 2
    Iteration number: 3
    Iteration number: 4
  • For the sum example:
    Sum from 1 to 5 is: 15
  • For the while loop with count < 3:
    Count is: 0
    Count is: 1
    Count is: 2
  • For the first do...while loop with number < 3:
    Number is: 0
    Number is: 1
    Number is: 2

Notice how do...while runs its body at least once, even if the condition is false. In the second do...while example with n = 5 and condition n < 3, the message still prints one time.

? Interactive Example

Click the button to see a simple for loop generate numbers from 1 to 5 and display them on the page.

? Demo Output

Click the button above to generate the numbers.

? Tips & Best Practices

  • Use for when you know the exact number of iterations.
  • Use for...in for enumerating object properties (keys).
  • Use for...of for iterating over iterable collections like arrays and strings.
  • Use while or do...while when the number of iterations depends on a condition that changes during runtime.
  • do...while ensures code runs at least once.
  • Avoid infinite loops by always updating the loop variable so the condition eventually becomes false.
  • Be careful using for...in on arrays; it may include unexpected keys or inherited properties.
  • Use break and continue intentionally to control loop flow (e.g., exit early or skip an iteration).

? Try It Yourself

  • Write a for loop to print even numbers from 2 to 20.
  • Use for...in to list keys of an object representing a car.
  • Use for...of to print each character of a string.
  • Create a while loop that counts down from 10 to 0.
  • Write a do...while loop that keeps asking a user for a password until it matches a stored password.