For Loop

Introduction

A for loop in JavaScript is used to repeat a block of code a specific number of times. It is one of the most commonly used loops and is especially useful when working with arrays, lists, or repetitive tasks.

Understanding how a for loop works helps developers write efficient and organized code.

What is a For Loop

A for loop runs code again and again until a defined condition becomes false. It is commonly used when the number of iterations is known before the loop starts.

Syntax

A for loop has three main parts initialization condition and increment or decrement

for (initialization; condition; increment) {
// code to execute
}

Initialization sets the starting point
Condition defines how long the loop will run
Increment updates the loop variable after each iteration

Example

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

This loop starts from 0 and runs until the value is less than 5 printing each step

How For Loop Works

First the initialization runs once
Then the condition is checked
If true the code inside the loop executes
After execution the increment updates the variable
The process repeats until the condition becomes false

Common Uses of For Loop

Looping through arrays
Displaying lists of data
Performing repeated calculations
Generating dynamic content on web pages

Looping Through an Array Example

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

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

This example prints each item from the array

Advantages

Simple and easy to use
Efficient for fixed repetitions
Improves code readability
Widely supported in all browsers

Best Practices

Use meaningful variable names
Avoid infinite loops by setting correct conditions
Keep loop code clean and readable
Use let instead of var for better scope control

Conclusion

The for loop is a fundamental concept in JavaScript that allows developers to repeat tasks efficiently. Mastering loops is essential for building dynamic and interactive applications.

Home ยป JavaScript Fundamentals (Beginner Level) > Loops > for Loop