Skip to content
the poor coder

loop array

Poor Man
Published
Reading time
2 min read
On this page

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#

Text
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#

Text
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:

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC