Skip to main content

JavaScript Loops

By SamK
0
0 recommends
Category(s)
Topic(s)

Loops in JavaScript are used to execute a block of code multiple times. There are several types of loops.

for Loop (Fixed Iterations)

Used when the number of iterations is known.

for (let i = 1; i <= 3; i++) {
   console.log(i);
}

// Output: 1 2 3

 while Loop (Condition-Based)

Used when the number of iterations is unknown.

let i = 1;
while (i <= 3) {
   console.log(i);
   i++;
}

// Output: 1 2 3

do...while Loop (Executes at least once)

Executes the code block at least once, even if the condition is false.

let i = 1;
do {
   console.log(i);
   i++;
} while (i > 5);

// Output: 1

 for...in Loop (Object Properties)

Iterates over the properties of an object.

const person = { name: "Alice", age: 25, city: "London" };
for (let key in person) {
   console.log(key + ": " + person[key]);
}

// Output: name: Alice age: 25 city: London

for...of Loop (Array Values)

Iterates over values in an array.

const colors = ["Red", "Green", "Blue"];
for (let color of colors) {
   console.log(color);
}

// Output: Red Green Blue

Break & Continue

  • break: Exits the loop completely.
  • continue: Skips the current iteration and continues with the next. 

Example

// break
for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    break; // Stops the loop when i equals 3
  }
  console.log(i);
}
// Output: 1, 2

// continue
for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skips iteration when i is 3
  }
  console.log(i);
}
// Output: 1, 2, 4, 5

Questions & Answers