How to Loop Through an Array in JavaScript
In this article, We will learn how to loop through array in Javascript.
A loop is a type of computer program that allows us to repeat a specific operation a predetermined number of times without having to write that operation individually.
For example, if we have an array and want to output each element in the array, rather than using the index number to do so one by one, we can simply loop through and perform this operation once.
forEach method
const arr = [1,2,3,4,5,6] const printValue = (curElement, index) =>{ console.log('Index :'+index+ ' Value :'+curElement) }
map method
arr.forEach(printValue) const arr1 = [1,2,3,4,5,6] arr1.map((curElement, index)=>{ return console.log('Index :'+index+ ' Value :'+curElement) })
for loop
const arr2 = [1,2,3,4,5,6] for(i=0;i<=arr2.length-1;i++){ console.log('Index :'+i+ ' Value :'+arr2[i]) }
for...in loop
const arr3 = [1,2,3,4,5,6] for (i in arr3) { console.log('Index :'+i+ ' Value :'+arr3[i]) }