For Loops
In JavaScript, a for loop is used to iterate over a collection of items, such as an array. It allows us to execute a block of code for each element in the collection.
A for loop consists of three parts:
- Initialization: Declare and initialize a loop variable, usually denoted as
i
. - Condition: Specify the condition under which the loop will continue executing.
- Increment: Update the loop variable after each iteration.
Here's an example of using a for loop to iterate over an array of colors and print each color on the console:
1// Iterating over an array using a for loop
2const colors = ['red', 'green', 'blue'];
3
4for (let i = 0; i < colors.length; i++) {
5 console.log(colors[i]);
6}
In this example, we initialize the loop variable i
to 0. Then, the loop continues executing as long as i
is less than the length of the colors
array. After each iteration, we increment i
by 1. Inside the loop, we access each color using the index i
and print it on the console.
For loops are commonly used when we need to perform a task a specific number of times or iterate over each element in a collection. They provide a convenient way to repeat a block of code based on a condition and help us automate repetitive tasks.
Now it's your turn to practice using a for loop. Try writing a for loop to iterate over an array of numbers and calculate their sum.
xxxxxxxxxx
// Iterating over an array using a for loop
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}