different ways to iterate over an array JavaScript

introduction

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

1 — using for loop :

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 :

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 :

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

4 — using while :

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:

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

conclusion :

--

--

👨‍💻 Software engineering student 🔥 JavaScript lover ☕ ReactJs 👩‍🔧 @redux/toolkit react-refux 🧠 Laravel tinker 🔥

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdelmalek Ennani

👨‍💻 Software engineering student 🔥 JavaScript lover ☕ ReactJs 👩‍🔧 @redux/toolkit react-refux 🧠 Laravel tinker 🔥