How to Loop Over an Array in JavaScript

Channel: Linux
Abstract: var arr = ["index <

This tutorial will help you to initialize an array using JavaScript and navigate to array with one by one elements in a loop. Here you will find two methods for navigating through an array in JavaScript.

Method 1 – Using For Loop

Sometimes you may like to use older ways that is easy to use. This is simple c programming like for loop, easy to use and works perfect.

&lt;script type=&quot;text/javascript&quot;&gt; var index; var arr = [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;]; for (index = 0; index &lt; arr.length; ++index) { console.log(arr[index]); } &lt;/script&gt;123456789&lt;script type=&quot;text/javascript&quot;&gt;    var index;   var arr = [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;];   for (index = 0; index &lt; arr.length; ++index) {      console.log(arr[index]);   } &lt;/script&gt;

Method 2 – Using forEach

The forEach function calls callbackfn function one time for each element present in the array, in ascending index order. This is also useful for navigating through an array.
JavaScript forEach() function is also useful for navigating though array elements.

&lt;script type=&quot;text/javascript&quot;&gt; var arr = [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;]; arr.forEach(function(entry) { console.log(entry); }); &lt;/script&gt;12345678&lt;script type=&quot;text/javascript&quot;&gt;    var arr = [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;];   arr.forEach(function(entry) {      console.log(entry);   }); &lt;/script&gt;

Ref From: tecadmin
Channels: jsjavascript

Related articles