Skip to content

JavaScript Loops

Loops: Automating Repetition

Loops are used when you want to execute a block of code multiple times without writing it over and over.

1. The "While" Loop

The loop continues as long as a condition is True. - Logic: "Keep washing the dishes while there are still dirty plates." - Danger: If the condition never becomes False, you get an Infinite Loop.

2. The "For" Loop

The loop runs for a fixed number of times or for every item in a collection. - Logic: "For every student in the class, give them a textbook."

Loop Control: Break & Continue

  • Break: Immediately stop the loop and exit.
  • Continue: Skip the rest of the current turn and jump to the next one.

Why use Loops?

Loops are the reason computers are powerful. They never get tired of doing the same thing 1,000,000 times!

1. For Loop

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

2. While Loop

while (i < 10) {
  text += "The number is " + i;
  i++;
}

3. For...In Loop (Objects)

The for...in statement loops through the properties of an Object.

const person = {fname:"John", lname:"Doe", age:25};

let text = "";
for (let x in person) {
  text += person[x]; // Access by key
}

4. For...Of Loop (Iterables)

The for...of statement loops through the values of an iterable object (Arrays, Strings, Maps, NodeLists).

const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let x of cars) {
  text += x;
}

For In vs For Of

  • For In: Iterates over keys/indices (0, 1, 2, "fname").
  • For Of: Iterates over values ("BMW", "John").
  • Use for...of for Arrays. Use for...in for Objects.