Back to all posts

JavaScript For Loop


JavaScript for loop is a fundamental construct that allows developers to iterate over a collection of elements. While simple for loops are widely understood, mastering the intricacies of complex for loops can significantly enhance your JavaScript skills. In this blog post, we’ll dive deep into the world of for loops, explore some challenging examples, and unravel their hidden potential.

Understanding the Basics:

Before we delve into complex examples. let’s quickly review the basic synsax of a `for` loop in JavaScript:

for(initialization; condition; iteration) {
    //Code to be executed
}
  1. Initialization: This is where you initialize the loop counter or any variable you need for the loop
  2. Condition: The loop continues execution as long as the condition is true.
  3. Iteration: The iteration step is executed at the end of each iteration, usually incrementing or decrementing the loop counter.

Loop Example 1: Fibonacci Sequence

The Fibonacci sequence is a classic mathematical sequence where each number is the sum of the two preceding ones. Let’s create a for loop to generate the Fibonacci sequence up to a specified number of terms

const numberOfTerms = 10;
let fibonacci = [0, 1];
for (let i = 2; i < numberOfTems; i++) {
    fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}

console.log(fibonacci); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Loop Example 2: Nested Loops Nested loops are powerful constructs that allow us to iterate over multiple dimensions of data. Let’s consider a scenario where we want to print a pattern of numbers in a triangular shape.

const numberOfRows = 5;

for (let i = 1; i <= numberOfRows; i++) {
  let pattern = "";

  for (let j = 1; j <= i; j++) {
    pattern += j + " ";
  }

  console.log(pattern);
}

/* Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/