How to Use the Modern JavaScript For Loop?

Estimated read time 2 min read

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:

  1. Initialization: let i = 0 declares a variable i and sets its initial value to 0. This variable is used as the counter for the loop.
  2. Condition: i < array.length checks if the value of i is less than the length of the array. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates.
  3. Iteration: i++ increments the value of i by 1 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.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply