Loop through an array in JavaScript [Every Method]

RELATED QUESTION : How do I format a date in JavaScript?

There are several ways to loop through an array in JavaScript. Here are a few common approaches:

  1. for‘ loop:
const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

This will loop through the array and print each element to the console.

  1. for...of‘ loop:
const arr = [1, 2, 3, 4, 5];

for (const element of arr) {
  console.log(element);
}

This will also loop through the array and print each element to the console.

  1. forEach()‘ method:
const arr = [1, 2, 3, 4, 5];

arr.forEach(element => {
  console.log(element);
});

This will also loop through the array and print each element to the console.

Which method you choose will depend on your specific needs and personal preference. The for loop and ‘for...of‘ loop are more traditional looping structures, while the ‘forEach()‘ method is a more modern, functional approach.

Leave a Comment