Loops and Iteration

Loops are fundamental in programming, allowing you to repeat a block of code multiple times. JavaScript provides several types of loops, each suited for different scenarios. Understanding loops helps in efficiently managing repetitive tasks.

The for Loop

The for loop is commonly used when you know the number of times you need to iterate. It consists of three parts: an initialization, a condition, and an increment or decrement.

Syntax
for (initialization; condition; increment) {
  // code to be executed
}
Example
for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}
// Output:
// Iteration: 0
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4

The while Loop

The while loop is used when you want to repeat a block of code as long as a condition remains true. It is useful when you don’t know in advance how many times the loop will run.

Syntax
while (condition) {
  // code to be executed
}
Example
let count = 0;
while (count < 3) {
  console.log("Count:", count);
  count++;
}
// Output:
// Count: 0
// Count: 1
// Count: 2

The do...while Loop

The do...while loop is similar to the while loop, except it executes the code block at least once before checking the condition.

Syntax
do {
  // code to be executed
} while (condition);
Example
let i = 0;
do {
  console.log("Value of i:", i);
  i++;
} while (i < 3);
// Output:
// Value of i: 0
// Value of i: 1
// Value of i: 2

The for...of Loop

The for...of loop is used to iterate over iterable objects such as arrays, strings, or other iterable collections. It is particularly convenient for working with arrays.

Syntax
for (element of iterable) {
  // code to be executed
}
Example
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
  console.log(fruit);
}
// Output:
// apple
// banana
// cherry

The for...in Loop

The for...in loop is used to iterate over the properties of an object. It is useful for accessing each key in an object.

Syntax
for (key in object) {
  // code to be executed
}
Example
let person = {
  name: "Alice",
  age: 30,
  city: "New York",
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 30
// city: New York

Breaking and Continuing Loops

  • break: Exits the loop immediately.
  • continue: Skips the current iteration and moves to the next one.
Example using break
for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break; // Exit the loop when i is 3
  }
  console.log(i);
}
// Output:
// 0
// 1
// 2
Example using continue
for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue; // Skip the iteration when i is 2
  }
  console.log(i);
}
// Output:
// 0
// 1
// 3
// 4

Iterating Over Arrays

Using loops to iterate over arrays is common in JavaScript programming. Below are a few ways to iterate over an array:

Example using for loop
let numbers = [10, 20, 30, 40];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
// Output:
// 10
// 20
// 30
// 40
Example using forEach method

The forEach method is a built-in array method that allows you to apply a function to each element in an array.

let numbers = [10, 20, 30, 40];
numbers.forEach(function (number) {
  console.log(number);
});
// Output:
// 10
// 20
// 30
// 40

You can also use arrow functions with forEach:

numbers.forEach((number) => console.log(number));

Summary of Loop Types

Loop TypeDescription
forIterates a set number of times. Suitable when the number of iterations is known.
whileRepeats as long as a condition is true. Suitable for uncertain iterations.
do...whileSimilar to while, but executes the block at least once.
for...ofIterates over iterable objects like arrays. Suitable for array elements.
for...inIterates over the properties of an object. Suitable for object keys.

Summary

In this section, you’ve learned about different looping techniques in JavaScript. Loops are powerful tools that help you execute code repeatedly, whether you’re working with known or unknown numbers of iterations. Knowing which type of loop to use in different situations helps you write more readable and efficient code.