A for loop is a control structure that repeats a block of code a specific number of times. The for loop is a very common control structure in JavaScript.
If you want to learn more, check out the Introduction to Programming Course
The syntax of the for loop in JavaScript is as follows:
for (initialization; condition; update)
{
// Instructions to execute in each iteration
}
initializationis executed at the start of the loop, typically used to initialize a variable.conditionis evaluated at the start of each iteration; if true, the code inside the loop is executed; if false, the loop is exited.updateis executed at the end of each iteration, typically used to update the value of a variable.
Basic Example
Let’s see a simple example where a for loop is used to print numbers from 1 to 10:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
In this example:
- The initialization
let i = 1sets the initial value ofito 1. - The condition
i <= 10ensures the loop runs whileiis less than or equal to 10. - The update
i++incrementsiby 1 after each iteration. - Inside the loop, we use
console.log()to print the current value ofito the console.
The result is that numbers from 1 to 10 will be displayed on the screen.
Modifying 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 even numbers, so only odd numbers would be printed to the screen.
Interrupting 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 further iteration is unnecessary.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // interrupt upon reaching 5
}
console.log(i);
}
In this case, the loop would run from 0, but the conditional would interrupt it upon reaching 5. So it would display 0, 1, 2, 3, and 4 on the screen.
Special Cases
It is possible to create more “unusual” versions of the for loop. In general, it’s not a good idea to do this. But I’m telling you about it, if only so that if you ever see it, you can give someone a hard time. 😉
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 Statements
In the initialization and update sections, you can include multiple statements separated by commas. This is useful when you need several control variables:
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(`i: ${i}, j: ${j}`);
}
Practical Examples
Generate 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++) { // 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 iterating over the elements of an array. Here is an example that sums all 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 a Different Step
The update value doesn’t 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'
}
Decrementing For Loop
The for loop can also be used to iterate in descending 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 aim to show how to use the for loop. It does not mean it’s the best way to solve the problem they address. Usually, there are better alternatives.
