How to loop through all the entries in an array using JavaScript?

September 29, 2022 No comments array foreach javascript tips solutions

Introduction

Sometimes, we'll like to loop through all the entries in an array using JavaScript.

In this post, we are going to learn how to loop through the entries in an array.

How to loop through all the entries in an array using JavaScript

There are several ways to loop through all the entries in an array:

  • using a for-of loop:

    for (const element of array) {
      console.log(element);
    }
    
  • using forEach (since ES5+):

    array.forEach(element => {
      console.log(element);
    });
    
  • using for loop:

    for (let index = 0; index < array.length; ++index) {
      const element = array[index];
      console.log(element);
    }
    
  • using for-in:

    for (const propertyName in array) {
      if (array.hasOwnProperty(propertyName)) {
          const element = array[propertyName];
          console.log(element);
      }
    }
    

Conclusion

To loop through all the entries in an array you can use several methods modern and old-fashioned.

{{ message }}

{{ 'Comments are closed.' | trans }}