beginner

Loops


For Loop

The for loop is widely used to execute a block of code a specific number of times. It consists of an initialization, a condition, and an increment or decrement. You can iterate however you want, forward, backwards, by one, by multiple.

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`); // This will write 5 times, from 0 to 4
}

If we want to skip any iteration in for loop we can do so with continue

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(`Iteration ${i}`); // This will write 4 times, 0,1,3,4 because we are skipping 2
}

And if we want to completely exit the loop at any time, we can do it with break

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    break;
  }
  console.log(`Iteration ${i}`); // This will write 2 times, 0,1  because we are exiting at 2
}

There can be multiple for loops nested. If that is the case then you can’t use the same variable name.

for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    console.log(`Iteration ${j}`); // This will write 5 times, from 0 to 4
    console.log(`Iteration ${i}`); // This will write 20 times, 5 times from 0 to 4
  }
}

While Loop

The while loop repeatedly executes a block of code as long as a specified condition evaluates to true.

let count = 0;
while (count < 3) {
  console.log(`Count: ${count}`);
  count++;
}

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once before checking the condition.

let userInput;
do {
  userInput = prompt("Enter a number greater than 10:");
} while (userInput <= 10);

For…of Loop

The for...of loop simplifies iterating through arrays and other iterable objects.

let colors = ["red", "green", "blue"];
for (let color of colors) {
  console.log(color);
}
// Above is same as
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

For…in Loop

The for...in loop iterates over the properties of an object.

let person = { name: "Alice", age: 30, city: "New York" };
for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

Nested Loops

You can nest loops to perform more complex iterations, such as iterating through a 2D array.

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
for (let row of matrix) {
  for (let number of row) {
    console.log(number);
  }
}

What now?

Now you know one additional way of working with what you’ve learned so far. Now all you need to do is, as always, pratice. Try to combine everything you’ve learned so far.

Previous Conditional statements
Next Functions