JavaScript(JS) for Loop

www.‮i‬giftidea.com

In JavaScript, a for loop is used to execute a block of code repeatedly until a specified condition is met. The basic syntax of a for loop is as follows:

for (initialization; condition; increment/decrement) {
  // Code to be executed
}

Here's what each part of the for loop syntax means:

  • initialization: This is where you initialize the loop counter. It is executed once before the loop starts.

  • condition: This is the condition that is checked before each iteration of the loop. If the condition is true, the loop continues to execute. If it is false, the loop stops.

  • increment/decrement: This is the code that is executed at the end of each iteration of the loop. It is typically used to update the loop counter.

Let's look at an example. Suppose you want to print the numbers 1 to 10 to the console using a for loop. Here's how you can do it:

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

In this example, we're using a for loop to iterate over the numbers 1 to 10. The let i = 1 statement initializes the loop counter to 1. The i <= 10 condition checks if the loop counter is less than or equal to 10. The i++ statement increments the loop counter by 1 at the end of each iteration.

You can use the break statement to exit a for loop prematurely, and the continue statement to skip the rest of the current iteration and move on to the next iteration.

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    break; // Exit the loop when i equals 5
  }
  if (i % 2 === 0) {
    continue; // Skip the rest of the code in the current iteration when i is even
  }
  console.log(i);
}

In this example, we're using the break statement to exit the loop when i equals 5. We're using the continue statement to skip the rest of the code in the current iteration when i is even. This means that only the odd numbers from 1 to 4 will be printed to the console.