different ways to iterate over an array JavaScript

introduction

Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end. and they are dynamic due that you can store values of different data types.

"The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations." by MDN

As a JavaScript developer, you will mostly work with arrays. Mastering arrays will sharpen your JavaScript skills due that arrays are an essential feature in all programming languages, not just JavaScript.

Now let's see how we can iterate over an array's values using JavaScript. let's assume that we have the following array :

const arr = [100 , 200 , 300 , 400 , 500];

1 - using for loop :

we iterate the index of the array using for loop starting from 0 to length of the array (arrayName.length) and access elements at each index.

code : 馃憞

const arr = [100 , 200 , 300 , 400 , 500];

for (let i=0 ; i < arr.length ; i++) {
        console.log(arr[i]); // output : 100 200 300 400 500
 }

2 - using for..in :

an other way to iterate over an array is by using for...in , each iteration returns a key (x) 路 The key is used to access the value of the key

code : 馃憞

const arr = [100 , 200 , 300 , 400 , 500];

for (let i in arr) {
        console.log(arr[i]); // output : 100 200 300 400 500
 }

3 - using for..of :

for...of is an other JavaScript feature that we can use to iterate over an array, each iteration returns a value not a key (the opposite of for..in)

code : 馃憞

const arr = [100 , 200 , 300 , 400 , 500];

for (let i of arr) {
        console.log(i); // output : 100 200 300 400 500
 }

4 - using while :

The while loop loops through a block of code as long as a specified condition is true

code : 馃憞

const arr = [100 , 200 , 300 , 400 , 500];

let i = 0;
while(i < arr.length) {
        console.log(arr[i]); // output : 100 200 300 400 500
        i++;
 }

5 - forEach method:

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements 馃槈

code : 馃憞

const arr = [100 , 200 , 300 , 400 , 500];

arr.forEach((val , idx) => {
     console.log(val);  //  // output : 100 200 300 400 500
})

conclusion :

thanks for reading this post 鉂わ笍
Stay tuned for my upcoming posts where I explain other arrays methods. -> don't forget to share with us other methods that you know in comments section below