JavaScript Loop Array Complete Tutorial

In this section, we will learn how to loop and iterate through the elements of an array in JavaScript.

Ways to Loop an Array in JavaScript

There are a couple of ways in which we can loop through the elements of an array and return its content.

These ways are:

Note: In this section, we will run examples via each of these methods and explain how they can be used to loop through the elements of an array. So if you’re not familiar with either of those methods, we suggest go to its related section to learn the details.

JavaScript for Loop Array

Each array has a property named `length` that returns the size of that array. So because via this property we can see how many elements are in the target array, we can create a loop that produces exactly the same range of integer values as the size of the target array (starting from the value 0). We can then use these values as the index number of the target array. Basically, in the body of the `for` loop we call the name of the array and via a pair of bracket `[]` on the right side of that name and assigning the generated numbers, we get each element of the target array.

Example: iterate array in JavaScript via for loop

const arr = [1,2,3,4,5];
  for (let i = 0 ; i < arr.length; i++){
    console.log(arr[i]);
  }

Output :

1

2

3

4

5

JavaScript for of Loop Array

The `for of` loop can iterate through an iterable object and return all its elements. So because an array is also an iterable object, we can apply the `for of` loop on it to get all its elements.

Example: iterate array in JavaScript via for of loop

const arr = [1,2,3,4,5];
 for (const value of arr){
   console.log(value);
 }

Output:

1

2

3

4

5

JavaScript Spread Operator and Array

The spread operator is also capable of iterating through all the elements of an iterable object. Again, because an array is also an iterable object, the spread operator can be applied to it as well.

Example: iterate array in JavaScript via spread operator

const arr = [1,2,3,4,5];
console.log(...arr);

Output:

1 2 3 4 5

Note: we don’t use the spread operator to run specific instructions for each element of the array.

JavaScript Array and forEach() Method

The `forEach` is a prototype method of the `Array` construct function and every array object has this method.

When calling the `forEach` method, we need to pass a reference of a function as the argument to this method. After that, the execution engine will pass each element to that function (that we set as the argument) and run the body of this function for each element.

Example: iterate array in JavaScript via forEach() method

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

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

Output:

1

2

3

4

5

Note: there are more into the `forEach` method. So we highly recommend checking the related section to fully learn how this method works.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies