JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Loop For


Loops are essential in programming for executing a block of code repeatedly based on a condition. The for loop in JavaScript is one of the most commonly used loops, especially when the number of iterations is known in advance. It allows developers to write concise, readable, and maintainable code for repetitive tasks.

This tutorial explains the for loop in detail, provides practical examples, highlights common mistakes, and shares best practices for efficient use.

Why the For Loop Is Important

The for loop is important because it allows you to:

  • Automate repetitive tasks, such as processing items in an array.

  • Control the number of iterations explicitly.

  • Reduce code duplication.

  • Improve readability compared to writing the same code multiple times.

  • Combine with arrays, strings, and other iterable structures effectively.

Without loops, you would have to manually write repeated code blocks, which is inefficient and error-prone.

Syntax

The basic syntax of a for loop is:

for (initialization; condition; increment/decrement) {
  // Code to execute in each iteration
}
  • Initialization – Sets up a counter variable, executed once before the loop starts.

  • Condition – Evaluated before each iteration; if true, the loop continues.

  • Increment/Decrement – Updates the counter after each iteration.

Example 1: Basic For Loop

for (let i = 0; i < 5; i++) {
  console.log("Iteration number: " + i);
}

Output:

Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4

Here, the loop starts with i = 0 and runs until i < 5. After each iteration, i is incremented by 1.

Example 2: Counting Down

for (let i = 5; i > 0; i--) {
  console.log("Countdown: " + i);
}

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

This demonstrates using the for loop to count backward by decrementing the counter.

Looping Through Arrays

The for loop is often used to iterate over arrays:

let fruits = ["Apple", "Banana", "Cherry"];

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

Output:

Apple
Banana
Cherry

You can access array elements using the loop counter and perform operations on them.

Nested For Loops

for loops can be nested inside each other for multi-dimensional operations:

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

Output:

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2

Nested loops are useful for working with matrices or multi-level data structures.

Practical Examples

Example 1: Sum of Numbers

let sum = 0;
for (let i = 1; i <= 10; i++) {
  sum += i;
}
console.log("Sum of numbers 1 to 10: " + sum);

Example 2: Generating a Pattern

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

Output:

*
**
***
****
*****

Example 3: Processing Array Values

let numbers = [10, 20, 30, 40];

for (let i = 0; i < numbers.length; i++) {
  numbers[i] *= 2; // Double each value
}
console.log(numbers); // [20, 40, 60, 80]

Example 4: Skipping Iterations

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // Skip even numbers
  console.log(i);
}

Output:

1
3
5
7
9

Common Mistakes

  • Forgetting to update the loop counter, resulting in an infinite loop.

  • Using the wrong comparison operator in the condition.

  • Accessing an array index out of bounds.

  • Overcomplicating nested loops without proper control.

  • Declaring the counter outside the loop unnecessarily.

Best Practices

  • Use let for loop counters to limit scope.

  • Avoid unnecessary nested loops if possible to reduce complexity.

  • Always ensure the loop condition will eventually become false.

  • Use .length dynamically for arrays instead of hard-coded values.

  • Consider for...of or array methods for cleaner iteration when appropriate.

Real-World Applications

  • Iterating through arrays or objects.

  • Calculating totals, averages, or summaries.

  • Generating patterns or reports.

  • Manipulating DOM elements in web applications.

  • Performing repeated tasks like animations or batch processing.

Summary of JS Loop For

The for loop in JavaScript is a powerful and flexible tool for repeating code a known number of times. It provides control over initialization, conditions, and counter updates, making it ideal for iterating arrays, generating patterns, or performing calculations. By understanding its syntax, avoiding common mistakes, and following best practices, developers can use for loops effectively in a wide range of applications, from simple scripts to complex data processing tasks.


Practice Questions

Q1. How do you print numbers from 1 to 10 using a for loop?

Q2. How can you loop through an array of strings using a for loop?

Q3. What is the role of the increment statement in a for loop?

Q4. How can you skip a particular iteration in a for loop using continue?

Q5. What happens if you forget to update the loop counter in a for loop?

Q6. How can you exit a for loop prematurely using break?

Q7. Write a for loop that prints only even numbers from 1 to 10.

Q8. How can you use a for loop to count backwards from 10 to 1?

Q9. Can you use a for loop to loop through a string’s characters? How?

Q10. Write a nested for loop to generate pairs like (1,1), (1,2), (2,1), (2,2).


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top