A for
loop is a control structure that repeats a block of code a specified 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 of the for
loop in JavaScript is as follows:
for (initialization; condition; update)
{
// Instructions to execute in each iteration
}
initialization
is executed at the start of the loop, usually used to initialize a variable.condition
is evaluated at the start of each iteration; if true, the code inside the loop is executed; if false, the loop is exited.update
is executed at the end of each iteration, usually used to update the value of a variable.
Basic example
Let’s look at 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 ofi
to 1. - The condition
i <= 10
ensures that the loop runs whilei
is less than or equal to 10. - The update
i++
incrementsi
by 1 after each iteration. - Inside the loop, we use
console.log()
to print the current value ofi
to the console.
The result is that the numbers from 1 to 10 will be displayed on the screen.
Modifying the flow of the loop
Skipping iterations with continue
The continue
statement is used to skip the current iteration and proceed 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 cause all even numbers to be skipped, so only odd numbers would be printed on the screen.
Exiting the loop with break
Using the break
statement allows you to exit the loop before the condition is met. This is useful in situations where a specific value is found and further iteration is not necessary.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // interrupt upon reaching 5
}
console.log(i);
}
In this case, the loop would execute from 0, but the conditional would interrupt it upon reaching 5. Therefore, the screen would display 0, 1, 2, 3, and 4.
Special cases
It is possible to create more “original” cases of the for
loop. In general, it is not a good idea to do so. But I mention it just so that if you ever see it, you can scold someone. 😉
Using 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 finished, which will be 5
.
Multiple declarations
In the initialization and update sections, you can include multiple declarations separated by commas. 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 for a specific number is generated using a for
loop.
let number = 5; // Number for which the multiplication table is generated
for (let i = 1; i <= 10; i++) { // Iterate 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 is 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}`);
Iterating with a different step
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) { // Increments '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 decreasing order:
for (let i = 10; i > 0; i--) { // Decrements '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 whether 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 meant to show how to use the for
loop. It does not mean that it is the best way to solve the problems they address. Typically, there are better alternatives.