Skip to main content

JavaScript For Loop

Introduction

The for loop is one of the most commonly used looping structures in JavaScript. It allows you to execute a block of code repeatedly based on a condition, making it perfect for tasks that require iteration over a sequence of elements or executing code a specific number of times.

A for loop gives you precise control over the iteration process by explicitly defining the initialization, condition, and iteration step. This makes it particularly useful when you know exactly how many times you want to execute a block of code.

Basic Syntax

The syntax of a for loop consists of three main parts enclosed in parentheses and separated by semicolons:

javascript
for (initialization; condition; increment/decrement) {
// code block to be executed
}

Let's break down these components:

  1. Initialization: Executed once before the loop starts. Typically used to initialize a counter variable.
  2. Condition: Evaluated before each loop iteration. If true, the loop continues; if false, the loop ends.
  3. Increment/Decrement: Executed after each loop iteration, usually to update the counter variable.

Basic For Loop Example

Here's a simple example that counts from 1 to 5:

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

Output:

1
2
3
4
5

How this works:

  1. First, let i = 1 initializes the variable i to 1.
  2. Then, the condition i <= 5 is checked. Since 1 is less than or equal to 5, the code block executes.
  3. The statement console.log(i) outputs the value of i.
  4. After the code block executes, i++ increments i by 1 (making it 2).
  5. Steps 2-4 repeat until i becomes 6, at which point the condition i <= 5 is false, and the loop terminates.

Iterating Through Arrays

One of the most common uses of for loops is to iterate through arrays:

javascript
const fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];

for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit ${i+1}: ${fruits[i]}`);
}

Output:

Fruit 1: Apple
Fruit 2: Banana
Fruit 3: Orange
Fruit 4: Mango
Fruit 5: Pineapple

Advanced For Loop Features

Multiple Initialization Variables

You can initialize multiple variables in the initialization part:

javascript
for (let i = 0, j = 10; i < 5; i++, j--) {
console.log(`i = ${i}, j = ${j}`);
}

Output:

i = 0, j = 10
i = 1, j = 9
i = 2, j = 8
i = 3, j = 7
i = 4, j = 6

Omitting Parts of the For Loop

You can omit any of the three parts of the for loop, but you must keep the semicolons:

javascript
// Initialization outside the loop
let i = 0;
for (; i < 5; i++) {
console.log(i);
}

// Omitting the increment (handling it inside the loop)
for (let i = 0; i < 5;) {
console.log(i);
i++;
}

// Creating an infinite loop (be careful!)
// for (;;) {
// // This will run forever unless broken
// if (condition) break;
// }

Nested For Loops

You can nest for loops inside one another to work with multi-dimensional data structures:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Print matrix elements
for (let i = 0; i < matrix.length; i++) {
let row = "";
for (let j = 0; j < matrix[i].length; j++) {
row += matrix[i][j] + " ";
}
console.log(row);
}

Output:

1 2 3 
4 5 6
7 8 9

Breaking and Continuing

You can control the flow within loops using break and continue statements:

  • break: Exits the loop entirely
  • continue: Skips the current iteration and moves to the next one
javascript
// Using break
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break; // Exit the loop when i equals 6
}
console.log(i);
}

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

Output of break example:

1
2
3
4
5

Output of continue example:

1
3
5
7
9

Practical Examples

Example 1: Sum of Numbers

Let's calculate the sum of numbers from 1 to n:

javascript
function sumToN(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

console.log(sumToN(5)); // Sum of numbers 1 to 5
console.log(sumToN(10)); // Sum of numbers 1 to 10

Output:

15
55

Example 2: Finding Elements in an Array

Let's create a function to find all occurrences of an element in an array:

javascript
function findAllOccurrences(array, element) {
const indices = [];

for (let i = 0; i < array.length; i++) {
if (array[i] === element) {
indices.push(i);
}
}

return indices;
}

const numbers = [2, 4, 6, 8, 6, 10, 6];
console.log(`Indices of 6: ${findAllOccurrences(numbers, 6)}`);

Output:

Indices of 6: 2,4,6

Example 3: Building a Pattern

Let's use nested for loops to build a pattern:

javascript
function buildTriangle(height) {
let result = "";

for (let i = 1; i <= height; i++) {
// Add spaces
for (let j = 1; j <= height - i; j++) {
result += " ";
}

// Add stars
for (let k = 1; k <= 2 * i - 1; k++) {
result += "*";
}

result += "\n";
}

return result;
}

console.log(buildTriangle(5));

Output:

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

Common Pitfalls and Best Practices

1. Off-by-one Errors

Be careful with your loop boundaries. If you're iterating over an array, remember that indexes start at 0 and end at length - 1.

javascript
const arr = ['a', 'b', 'c'];
// Correct way:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

2. Modifying the Counter Inside the Loop

Avoid modifying the counter variable inside the loop body, as it can lead to unexpected behavior:

javascript
// Avoid this pattern
for (let i = 0; i < 5; i++) {
console.log(i);
i++; // This will cause the loop to skip values
}

3. Performance Considerations

For performance-critical operations, especially with large arrays, cache the array's length instead of computing it each iteration:

javascript
const arr = [/* large array */];
// More efficient:
for (let i = 0, len = arr.length; i < len; i++) {
// Code here
}

When to Use For Loops

Use for loops when:

  1. You know the exact number of iterations in advance
  2. You need to iterate through an array using indexes
  3. You need precise control over the iteration process
  4. You want to iterate backwards or with a custom step

For simpler array iterations, consider using forEach, for...of, or array methods like map, filter, and reduce.

Summary

The for loop is a fundamental control flow structure in JavaScript that allows you to execute code repeatedly based on specific conditions. Its flexibility and precise control make it an essential tool for any JavaScript developer, especially when working with arrays and other iterable data structures.

Key points to remember:

  • The for loop has three parts: initialization, condition, and increment/decrement
  • It's commonly used for array iteration, counting, and building patterns
  • You can nest for loops for working with multi-dimensional data
  • Use break and continue to control the flow within the loop
  • Consider other iteration methods like forEach and for...of for simpler use cases

Exercises

  1. Write a for loop that prints all even numbers from 0 to 20
  2. Create a function that reverses an array using a for loop
  3. Use nested for loops to create a multiplication table for numbers 1 to 10
  4. Write a function that checks if a string is a palindrome using a for loop
  5. Create a function that finds the largest element in a nested array using for loops

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)