Language: EN

javascript-bucle-for

What is and how to use the FOR loop in JavaScript

A for loop is a control structure that repeats a block of code a predetermined number of times. The for loop is a very common control structure in JavaScript.

If you want to learn more about Loops
check the Introduction to Programming Course read more ⯈

The syntax for the for loop in JavaScript is as follows:

for (initialization; condition; update)
{
    // Instructions to be executed in each iteration
}
  • initialization is executed at the beginning of the loop, usually used to initialize a variable.

  • condition is evaluated at the beginning of each iteration, if it is true the code inside the loop is executed, if it is false it exits the loop.

  • increment is executed at the end of each iteration, usually used to update the value of a variable.

Basic Example

Let’s see a simple example where a for loop is used to print the numbers from 1 to 10:

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

In this example:

  • The initialization let i = 1 sets the initial value of i to 1.
  • The condition i <= 10 ensures that the loop runs while i is less than or equal to 10.
  • The update i++ increments i by 1 after each iteration.
  • Inside the loop, we use console.log() to print the current value of i to the console.

The result is that the numbers from 1 to 10 will be displayed on the screen.

Modifying the loop flow

Skipping iterations with continue

The continue statement is used to skip the current iteration and move directly to the next iteration of the loop.

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

In the example, the conditional would skip all the even numbers, so only the odd numbers would be printed on the screen.

Breaking the loop with break

Using the break statement allows exiting the loop before the condition is met. This is useful in situations where a specific value is found and there is no need to continue iterating.

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;  // Interrupt when reaching 5
    }
    console.log(i);
}

In this case, the loop would run from 0, but the conditional would interrupt it when it reaches 5. So it would display 0, 1, 2, 3, and 4 on the screen.

Special Cases

It is possible to carry out more “original” cases of the for loop. In general, it is not a good idea to do so. But I’ll tell you about it, if only to tell someone off if you ever see it. 😉

Use of external variables

It is possible to use a variable declared outside the for loop as the control variable. However, this can lead to confusion and errors if not managed properly:

let i = 0;
for (i = 0; i < 5; i++) {
    console.log(i);
}
console.log(`Value of i after the loop: ${i}`);

In this case, i retains its value after the loop has ended, which will be 5.

Multiple declarations

In the initialization and update section, multiple statements separated by commas can be included. This is useful when multiple control variables are needed:

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

Practical Examples

Generating a multiplication table

In this example, a multiplication table is generated for a specific number using a for loop.

let number = 5; // Number for which the multiplication table is generated

for (let i = 1; i <= 10; i++) { // Iterates from 1 to 10
    console.log(`${number} x ${i} = ${number * i}`); // Prints the multiplication of the number by 'i'
}

Iterating over Arrays

One of the most common applications of the for loop is to iterate over the elements of an array. Here’s an example that sums all the elements of an array:

let numbers = [1, 2, 3, 4, 5]; // Declare the array
let sum = 0; // Variable to store the sum

for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i]; // Add each element of the array to 'sum'
}

console.log(`The sum of the elements is: ${sum}`);

Iteration with different steps

The value of the update does not always have to be an increment of one. It can be any expression that modifies the control variable. For example, iterating in steps of two:

for (let i = 0; i < 10; i += 2) { // Increment 'i' by 2 in each iteration
    console.log(i); // Prints the current value of 'i'
}

Decreasing for loop

The for loop can also be used to iterate in descending order:

for (let i = 10; i > 0; i--) { // Decrease 'i' by 1 in each iteration
    console.log(i); // Prints the current value of 'i'
}

Searching for an element in an Array

let numbers = [1, 2, 3, 4, 5]; // Declare the array
let search = 3; // Number to search for
let found = false; // Variable to indicate if the number was found

for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] === search) { // Compare each element with the searched number
        found = true; // Mark that the number was found
        break; // Exit the loop
    }
}

if (found) {
    console.log(`The number ${search} is in the array.`);
} else {
    console.log(`The number ${search} is not in the array.`);
}

These examples are intended to show how to use the for loop. It does not mean that it is the best way to solve the problem they address. Normally there are better alternatives.