Loops are used to write repeatable code in a programming language.
This article will focus on the JavaScript for
loop. It is one of the commonly used loops in the language.
We’ll discuss the basic for
loop syntax and how you can use it in your code.
What Is a For Loop?
A for
loop is a JavaScript statement used to iterate code several times until a condition is met. It has three optional statements written in parentheses separated by semicolons.
This is the syntax for the for
loop:
for(initialization; condition; initializationUpdater) {
block statement;
}
Initialization
Initialization is the first expression inside a for
loop’s parentheses, it initializes a counter variable, and it is only evaluated once, at the beginning of the loop.
Multiple variables can be declared in the initialization, but it is better to limit it to two for the readability and maintainability of the code. It all depends on the author or what the loop is to be used for.
While declaring a variable, it is better to use the let
keyword as seen in the above example to keep it in the local scope, using var
will put it in a global scope and at risk of name conflicts.
Now the optional part means that the for
loop can be written without the initialization.
let i = 0;
for(; i < 5; i++) {
console.log(i);
}
//output: 0 1 2 3 4
It is an option but in this case, it is better to use the while
loop.
Condition
The condition is an expression to be evaluated before each iteration. If the condition is true
then the statement is executed. If it is false
the loop stops running and moves to the next statement after the loop.
InitializationUpdater
This part updates the initialization expression after checking the condition and ensuring it is true. It could be an increment (++
) or decrement (--
) operator.
for(initialization; condition; i++) {
block statement;
}
It can also be incremented in either evens or odds by using the addition assignment (+=
) operator and adding the number you want to increase.
for (i = 2; i <= 10; i+=2) {
console.log(i)
}
// output: 2 4 6 8 10
Now it adds 2 to the initial 2 declared in the index i
. Once it gets to 10, the loop terminates just like I stated above.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
The console will log out something like this:
0
1
2
3
4
It stops at four(4
) because, in the above condition, the index i
is less than the number in the condition (5
). It can’t get up to that number because it makes the condition false
hence the loop is terminated once it gets to a number less than the condition’s.
Think of a JavaScript for
loop like a box with a capacity to hold 5 candies. You start with an index of 0, and after each candy is placed, the loop checks if there’s space for more. When the index reaches 4, the loop realizes that adding another candy would exceed the box's capacity, so it stops automatically and moves on to the next task.
The above case applies unless the index matches the condition's number.
Like this:
for (let i = 0; i <= 5; i++) {
console.log(i);
}
Now in this statement, the index i
is less than or equal to (<=
) the number of the condition. Therefore the result will be different from when it was just less than the condition's number.
In this case, 5 candies can now fit perfectly inside the box.
0
1
2
3
4
5
How to Loop Through an Array
A for
loop can also loop through an array
to output the list into the desired location using the length
property.
It can be done with this syntax:
const cars = ["Mustang", "Ferrari", "Lamborghini"];
for(i = 0; i < cars.length; i++){
console.log(cars[i])
}
// output: Mustang Ferrari Lamborghini
In the output, the loop
logs out the array
values after iterating through it. This is done by setting the index to 0, this ensures that the index is less than the elements in the array
and that the loop
runs until that condition is false
.
Now, the index acts as a placeholder for the elements in the array
.
The index moves to another element each time the loop
increments by one after each iteration.
Then it prints that element out in the console. This is done until it prints all the elements in that array
.
Conclusion
This article covered what for loop is, what it is used for, and its basic syntax.
It explained the for loop expressions, their functions, and how to iterate through an array using the for loop.
For loop is an essential tool in JavaScript, and it is important to know how it works to use it best.