In JavaScript, there are several ways to loop through an array or other iterable object. One of the most commonly used is the for
loop. The modern syntax for the for
loop in JavaScript is as follows:
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
In the example above, the for
loop has three parts separated by semicolons:
- Initialization:
let i = 0
declares a variablei
and sets its initial value to0
. This variable is used as the counter for the loop. - Condition:
i < array.length
checks if the value ofi
is less than the length of thearray
. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates. - Iteration:
i++
increments the value ofi
by1
after each iteration of the loop.
The code inside the loop body { ... }
is executed for each iteration of the loop. In the example above, the value of array[i]
is logged to the console for each iteration of the loop.
Here’s another example that uses the modern syntax of the for
loop to sum the elements of an array:
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // Output: 15
In this example, the for
loop is used to iterate through the numbers
array and add each element to the sum
variable. The final result, 15
, is the sum of all the elements in the numbers
array.
+ There are no comments
Add yours