loop array

Looping Through an Array in JavaScript

If you have a collection of values that you want to iterate over, you can use an array in JavaScript. An array is a special variable that can hold multiple values at once. You can access individual elements in an array using an index number.

There are several ways to loop through an array in JavaScript. Here are two common methods:

Method 1: for Loop

const myArray = [1, 2, 3, 4, 5];

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

In this example, we create an array called myArray with five elements. We then use a for loop to iterate over the array. The loop starts at index 0 and continues until the index is less than the length of the array. Inside the loop, we use the index variable (i) to access the current element in the array and log it to the console.

Method 2: forEach Method

const myArray = [1, 2, 3, 4, 5];

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

In this example, we again create an array called myArray with five elements. This time, we use the forEach method to loop over the array. The forEach method takes a function as its argument. This function is called once for each element in the array, and the current element is passed as an argument to the function. Inside the function, we log the current element to the console.

Both of these methods will produce the same output:

1
2
3
4
5

Choose the method that works best for your particular use case. The for loop is more flexible and can be used with other types of collections besides arrays, but the forEach method is more concise and easier to read.

Conclusion

Looping through an array in JavaScript is a common task that you will encounter as a web developer. By using the for loop or the forEach method, you can easily iterate over the elements in an array and perform whatever operations you need to on each element.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe