Javascript Control Flow

JavaScript for loop


In programming, loops are essential for repeating a block of code. JavaScript provides various loop structures, and one of the most commonly used is the for loop. Let's delve into the syntax and usage of the for loop in JavaScript: syntax:

for (initialExpression; condition; updateExpression) {
    // Code block to be executed repeatedly
}

* The initialExpression initializes and/or declares variables and executes only once at the beginning of the loop. * The condition is evaluated before each iteration. If it evaluates to true, the loop continues; if false, the loop terminates. * The updateExpression updates the value of the loop control variable at the end of each iteration.

Working Principle:

1. The initialExpression is executed. 2. The condition is evaluated. If true, the loop body is executed; if false, the loop terminates. 3. After each iteration, the updateExpression is executed. 4. Steps 2 and 3 are repeated until the condition becomes false.

Example 1: Displaying Text Five Times

const n = 5;

for (let i = 1; i <= n; i++) {
    console.log(`I love JavaScript.`);
}

In this example, the loop iterates from i = 1 to i = 5, printing "I love JavaScript." each time.

Example 2: Displaying Numbers from 1 to 5

const n = 5;

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

Here, the loop iterates from i = 1 to i = 5, printing the value of i in each iteration.

Example 3: Displaying Sum of n Natural Numbers

let sum = 0;
const n = 100;

for (let i = 1; i <= n; i++) {
    sum += i;  // Equivalent to: sum = sum + i
}

console.log('sum:', sum);

This example calculates the sum of the first n natural numbers (1 + 2 + 3 + ... + 100) using a for loop.

Infinite Loop:

for(let i = 1; i > 0; i++) {
    // Block of code
}

If the condition in a for loop is always true, it results in an infinite loop, which runs until the program is terminated. The for loop is a powerful construct for iterating over a range of values or performing a specific task a certain number of times. It's extensively used in JavaScript programming for various tasks, including data processing, iteration, and automation.