🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

For Loops

JavaScript For Loop

JavaScript For Loop

A for loop is a control flow statement in programming that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax of a for loop consists of three parts: initialization, condition, and iteration. Here's the basic structure:

for (initialization; condition; iteration) {
  // Code to be executed in each iteration
}
  1. Initialization: Typically, this part is used to initialize a counter variable. It runs once at the beginning of the loop.
  2. Condition: The loop continues as long as this condition is true. If the condition evaluates to false, the loop exits.
  3. Iteration: This part is executed after each iteration of the loop. It is commonly used to update the counter variable.

Example:

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

In this example:

  • let i = 1 initializes a counter variable i to 1.
  • i <= 5 is the condition that specifies when the loop should continue.
  • i++ increments the counter variable by 1 after each iteration.

The loop will execute five times, printing the numbers 1 to 5.

Examples:

Iterating Over an Array:

const fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Nested Loops:

for (let i = 1; i <= 3; i++) {
  for (let j = 1; i <= 3; j++) {
    console.log(`i: ${i}, j: ${j}`);
  }
}

Skipping Iteration (using continue):

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip iteration when i is 3
  }
  console.log(i);
}

Breaking Out of a Loop (using break):

for (let i = 1; i <= 5; i++) {
  if (i === 4) {
    break; // Exit the loop when i is 4
  }
  console.log(i);
}

for loops are powerful constructs for iterating over sequences, such as arrays, and performing repetitive tasks. They are widely used in programming to automate processes that involve repetitive actions.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.