JavaScript for Loop
Master the JavaScript for loop with clear explanations, professional definitions, and practical examples used in real-world programming.
In JavaScript, a for loop is a fundamental control structure used to execute a block of code repeatedly as long as a specified condition remains true. It is commonly used when the number of iterations is known in advance, making it one of the most widely used loops in modern JavaScript development.
A for loop consists of three essential components: initialization, condition, and increment or decrement. These components work together to control how many times the loop runs.
Syntax of the JavaScript for loop:
for(initialization; condition; increment/decrement){
// code to be executed
}
Initialization: This step is executed only once, before the loop begins. It is typically used to declare and initialize a counter variable that tracks the loop iterations.
Condition: The condition is evaluated before each iteration of the loop.
If the condition evaluates to true, the loop continues executing.
If it evaluates to false, the loop stops immediately.
Increment / Decrement: This expression updates the counter variable after each iteration. It ensures that the loop moves toward termination and prevents infinite loops.
Example 1: Basic JavaScript for Loop
In this example, the loop starts with an initial value of 0 and runs until the value
of i is less than 5. After each iteration, the value of i
increases by 1. The result is printed to the browser console.
JavaScript for Loop Explained with Examples
In JavaScript, a for loop is a powerful control structure that allows you to execute a block of code multiple times based on a defined condition. It is especially useful when working with arrays, numerical ranges, and repetitive tasks.
A standard for loop consists of three key parts: initialization, condition, and increment or decrement.
Syntax of the for loop:
for(initialization; condition; increment/decrement){
// code to be executed
}
Initialization: Runs once before the loop starts and is typically used to declare a counter variable.
Condition: Checked before each iteration. If the condition evaluates to true,
the loop continues running.
Increment / Decrement: Updates the counter variable after each iteration, ensuring the loop progresses and eventually stops.
Example 1: Loop through an array
JavaScript Example
let fruits = ["Apple", "Banana", "Orange", "Mango"];
for(let i = 0; i < fruits.length; i++){
console.log(fruits[i]);
}
Try it Yourself ยป
Explanation: This example demonstrates how a for loop
is commonly used to iterate through an array. The loop starts at index 0
and continues until it reaches the last element of the array.
Example 2: Calculate the sum of numbers
JavaScript Example
let sum = 0;
for(let i = 1; i <= 10; i++){
sum += i;
}
console.log("Total Sum:", sum);
Try it Yourself ยป
Explanation: In this example, the loop adds numbers from 1
to 10. The variable sum stores the accumulated result,
which is commonly used in calculations, reports, and analytics.
Example 3: Nested for Loop in JavaScript
A nested for loop is a loop that exists inside another loop. This programming structure is widely used when working with tables, grids, matrices, multi-dimensional arrays, or when a task needs to be repeated across multiple levels.
In a nested loop, the inner loop runs completely for each single iteration of the outer loop. This means the total number of executions depends on how many times both loops run.
JavaScript Syntax Example
General Syntax: The outer loop controls the main iteration, while the inner loop performs repeated actions for each outer loop cycle.
for (initialization; condition; increment/decrement) {
for (initialization; condition; increment/decrement) {
// code to be executed
}
}
Practical Example: The following example generates a 3 ร 3 multiplication grid. The outer loop controls the rows, while the inner loop calculates the values inside each row.
for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += (i * j) + " ";
}
console.log(row);
}
Try it Yourself ยป
How it works:
โข The outer loop (i) runs from 1 to 3 and represents each row.
โข The inner loop (j) also runs from 1 to 3 and calculates values for each column.
โข The result is printed row by row, forming a multiplication table.
Frequently Asked Questions About JavaScript for Loops
What is a for loop in JavaScript?
A for loop in JavaScript is a fundamental control structure
that allows a block of code to be executed repeatedly as long as a specified
condition evaluates to true.
It is most commonly used when the number of iterations is known in advance, such as looping through numeric ranges, iterating over arrays, or generating structured output like tables and patterns.
When should I use a for loop instead of while?
You should use a for loop when the number of iterations is predictable or fixed, such as iterating over an array or running a loop a specific number of times.
A while loop is more suitable when the loop depends on a condition that may change dynamically during execution and the total number of iterations is not known beforehand.
What is a nested for loop in JavaScript?
A nested for loop is a loop placed inside another loop. The inner loop executes fully for each iteration of the outer loop.
Nested loops are frequently used when working with tables, grids, matrices, multiplication charts, and other multi-dimensional data structures where rows and columns must be processed together.
How do you loop through an array in JavaScript?
You can loop through an array in JavaScript using a for loop
by accessing each element through its index, starting from 0
up to array.length - 1.
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
In modern JavaScript, alternative approaches such as forEach(),
for...of, and map() are also commonly used, depending
on readability, performance needs, and coding style.
What are common mistakes with JavaScript for loops?
- Forgetting to update the loop counter, which can result in infinite loops
- Using incorrect loop conditions, such as
<=instead of< - Accessing array elements outside the valid index range
- Declaring loop variables with
varinstead ofletorconst - Creating unnecessary nested loops that negatively impact performance