JavaScript For Loop

JavaScript For Loop

In JavaScript, a for loop allows you to repeat a block of code again and again in your program. It’s like checking every item in the list or repeating any task multiple times. In this blog, we will discuss what JavaScript for loop is, how it works, and how you can use it in your code.

Table of Content

What is JavaScript For Loop?

JavaScript is a programming language that will help you make your website interactive. It provides you with various features to help you code and for loop is one of those. The JavaScript for loop will help you repeat a block of code multiple times in your code. It allows you to repeat the code for each item in a list or range.

Syntax of JavaScript For Loop

The syntax of the JavaScript for loop is very straightforward but it’s important to know and  understand the working of a for loop.

for (initialization; condition; update) {
  // Code
}

The for loop contains three main statements which are:

  1. Initialization
  2. Testing Condition
  3. Increment/Decrement (Update)

Let’s see in detail what they do:

Statement 1: Initialization

Initialization is the first step in the for loop process where you define the loop variable to a starting value. This will be executed at the beginning of the loop. The main purpose of the initialization is to initialize the variable that will be used in the for loop.

Example:

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

Here,

  • let i = 5; is the initialization step. 
  • It will set the loop variable ‘i’ to 5 which means the loop will start from 5.

Output:

Statement 2: Testing Condition

After initialization comes the condition. It is the second part in the for loop. It checks if the loop should keep running or not. The loop will run as long as the condition is true and it will stop when the condition is false.

Example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; 
  }
  console.log(i);
}

Here,

  • The condition is i < 10.
  • So the loop will run as long as ‘i’ is less than 10.
  • But we have another condition to check,
    if (i === 5) {
      break;
    }
  • So, the loop will stop when ‘i’ equals 5, even if the first condition i < 10 is still true.

Output:

Statement 3: Increment/Decrement

The last step in the for loop is increment/decrement. It happens after each iteration of the for loop. It will change the value of the variable either increase it or decrease it. After changing the value, the loop will run again and again until it matches the condition to stop.

  • i++; it will increase the value by 1.
  • i–; it will decrease the value by 1.

Example:

for (let i = 10; i >= 5; i--) {
  console.log(i);
}

Here,

  • The loop will start when i = 10 and runs as long as i >= 5.
  • After each iteration, i– will decrease the value of ‘i’ by 1

Output:

Flowchart of JavaScript For Loop

The flowchart represents the repetitive cycle of JavaScript for loop and shows how it checks the condition, executes the code, and how a variable gets changed before the cycle restarts. Let’s see how it works:

  1. Start: The loop will start and initialize the variable in the loop.
  2. Checks Condition: The loop will check the condition and if the condition is true then the loop will continue otherwise the loop will stop when the condition is false.
  3. Increment/Decrement: The variable in the loop will update either increase or decrease and the loop will continue this process.
  4. Halt: The loop will stop when the condition is false.

JavaScript Infinite For Loop

An infinite loop happens when the condition is always true so the loop will run forever. In a regular for loop, the condition will eventually become false and stop the loop but in an infinite for loop, the condition will never be false.

Example:

for (let i = 0; i >= 0; i++) {
    console.log(i);
}

Explanation:

  • Since the value of ‘i’ is 0 and increasing. According to i >= 0, the value of ‘i’ should be greater than 0 which makes the condition always true. Hence, the condition will never be false and the loop will run forever.

Output:

0
1
2
3
…

Types of Loops in JavaScript

In JavaScript, there are many different types of loops. Let’s see how they are different from each other:

  1. for loop: This loop will run only a set number of times depending on the conditional expression.
  2. while loop: This loop will run until the condition becomes false. It will check the condition in each iteration.
  3. do…while loop: This is very similar to the while loop but it will run at least once and then continue as long as the condition is true.
  4. for…in loop: This loop iterates over the properties of an object.
  5. for…of loop: This loop iterates over the values of an object like an array or a string.

Performance Comparision: For vs Other Loops

Loop TypePerformanceUse CaseNotes
for loopFastestIt is best when you are using arrays and when you need index control.It is a good choice for performance-sensitive tasks.
while loopSimilar to for loopIt is best when you know the number of iterations.It is more flexible compared to the for loop.
do…while loopSimilar to while loopIt is best when you need to run the loop at least once before checking the condition.It will run at least once regardless of the condition.
for…in loopSlowestIt is best when the loop is iterating over object properties.It is slower when you are working with arrays.
for…of loopSlower than the for loopIt is best when the loop is iterating over the values of an object like an array or a string.It is more readable than the for loop but slower.

For Loop in Modern JavaScript

1. for…in Loop

The for…in loop is used to iterate over the properties of an object. It is slower when you are working with arrays.

Syntax:

for (let key in object) {
  console.log(key, object[key]);
}

2. for…of Loop

The for…of loop is used to iterate over the values of an object like an array or a string. It is more readable than the normal for loop but slower.

Syntax:

for (let value of iterable) {
  console.log(value);
}

Advanced Use Cases of For Loop

For loop is a very versatile loop in JavaScript. Even though it has very basic usage, you can also use it in some advanced use cases. Here are some examples:

1. Looping Backwards Efficiently

It means starting the for loop from the last item in an array and moving backward to the first item.

Use cases:

  • It is used when you need to add or remove items from an array in reverse order.
  • It can help you avoid issues when modifying the array while looping.

Example:

let arr = [1, 2, 3, 4, 5];
for (let i = arr.length - 1; i >= 0; i--) {
  console.log(arr[i]);
}

Output:

2. Looping with Multiple Variables

It means instead of using only one variable, use multiple variables in the for-loop to track different things at the same time.

Use cases:

  • It is used when you want to loop over multiple things at the same time like two arrays or different counters.
  • You can use it to update different variables at the same time.

Example:

let arr1 = [1, 2, 3];
let arr2 = ['a', 'b', 'c'];
for (let i = 0, j = 10; i < 5; i++, j -= 2) {
  console.log(`i: ${i}, j: ${j}`);
}

Output:

Common Mistakes to Avoid

Even though for loop has a very basic structure and is easy to understand, there are some mistakes people normally make. Here are some common mistakes you should avoid:

1. Off-by-one error (wrong loop condition)

It happens when the loop runs one extra time or does not run enough times.

Example:

for (let i = 0; i <= 10; i++) {   // It will run 11 times instead of 10
    console.log(i);
}

How to fix: You have to make sure the loop ends at the right time.

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

2. Infinite loop (forgetting to update the loop variable)

It happens when you forget to update the loop variable which makes the loop run infinitely.

Example:

for (let i = 0; i < 10;) {  // Missing 'i++', so the loop never ends
    console.log(i);
}

How to fix: You have to make sure the loop variable gets updated.

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

3. Not breaking early when needed

It happens when you do not stop the loop even though you have got the desired outcome.

Example:

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 3) {
        // code
    }
}

How to fix: You can use the break statement to stop the loop early.

for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 3) {
        // code
        break;   // Stop the loop
    }
}

Conclusion

So far in this blog, we have learned what JavaScript for loop is, how it works, and how you can use it in your code. For loop in JavaScript allows you to repeat the code for each item in a list or range. JavaScript provides many different loops other than the for loop like the while loop, do-while loop, etc. We also discussed what an infinite for loop is and why it happens.

FAQs – JavaScript For Loop

1. What is a JavaScript for loop?

The JavaScript for loop will help you repeat a block of code multiple times in your code. It allows you to repeat the code for each item in a list or range.

2. What is the basic syntax of JavaScript For Loop?

The for loop contains three main statements which are:

  1. Initialization
  2. Condition
  3. Update
for (initialization; condition; update) {...}
3. Define the parts of a for loop.

The for loop is divided into 3 parts:

  1. Initialization: It is the first step in the for loop where you define the loop variable to a starting value.
  2. Testing Condition: It checks if the loop should keep running or not by checking the condition in each iteration.
  3. Increment/Decrement: It will change the value of the variable either increasing it or decreasing it.
4. What happens if you don't update the loop variable?

If you don’t update the loop variable using ‘i++’ or ‘i–‘ then the loop will run forever and it will create an infinite for loop.

5. What is an infinite for loop?

An infinite loop happens when the condition is always true so the loop will run forever. Compared to a regular for loop which will eventually stop when the condition is false but in an infinite for loop, the condition will never be false.

6. Can I skip an iteration of the loop?

Yes, you can skip the iteration using the ‘continue’ statement and move to the next loop.

7. Can I exit a for loop early?

Yes, you can exit the for loop early using the ‘break’ statement.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner