How to loop through array in Javascript?

In JavaScript, you can loop through an array using different kinds of loops. Here are three commonly used methods:

  1. For loop: You can use a for loop to iterate over each element of the array. The syntax is as follows:
const arr = ['apple', 'banana', 'cherry'];

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

In this example, we initialize a for loop with a variable i set to 0. The loop will continue as long as i is less than the length of the array, and on each iteration, i is incremented by 1. Inside the loop, we use the console.log() method to print out each element of the array.

  1. For…of loop: You can use a for…of loop to iterate over the values of the array. The syntax is as follows:
const arr = ['apple', 'banana', 'cherry'];

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

In this example, we use a for…of loop to iterate over each element of the array. Inside the loop, we use the console.log() method to print out each element of the array.

  1. Array.forEach() method: You can use the forEach() method of the array to iterate over each element of the array. The syntax is as follows:
const arr = ['apple', 'banana', 'cherry'];

arr.forEach(function(element) {
  console.log(element);
});

In this example, we use the forEach() method to iterate over each element of the array. Inside the method, we use a callback function to print out each element of the array.

All three of these methods accomplish the same task of iterating over an array, but the syntax and usage can differ depending on your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *