How to loop through an array in JavaScript?
How to loop through an array in JavaScript?
For loop is the best method for looping or iterating over an array in js.
for ex:
<script> var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"]; // Loop through the fruits array and display all the values for(var i = 0; i < fruits.length; i++) { document.write("<p>" + fruits[i] + "</p>"); } </script>
or
<script> var fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"]; // Loop through the fruits array and display all the values for(var fruit of fruits) { document.write("<p>" + fruit + "</p>"); } </script>
It works like this:
// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
// ... do something with s ...
}
Or better yet, since ECMAScript 2015 also provides block-scoped variables via let
and const
:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
Some JavaScript developers are still working in an environment that’s not there yet, however – especially if writing code to run in web browsers, where the site developers often can’t be sure what browser/version their clients will be using.
If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach
iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:
var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) {
// ... do something with s ...
} );
But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
if (i in myStringArray) {
s = myStringArray[i];
// ... do something with s ...
}
}
Assigning the length value to the local variable (as opposed to including the full myStringArray.length
expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.
You will often see the length caching done in the loop initialization clause, like this:
var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {
The for
…in
syntax mentioned by others is for looping over an object’s properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length
property), you can theoretically loop over an Array with it. But the problem is that it doesn’t restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for
…in
syntax should not be used for looping through Arrays.
<script>
array = [
'geeks'
,
'4'
,
'geeks'
];
// Accessing array elements one by one
console.log(array[0]);
console.log(array[1]);
console.log(array[2]);
</script>
Output:
geeks 4 geeks
There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below.
Using for loop.
This is similar to for loops in other languages like C/C++, Java, etc
<script> array = [ 1, 2, 3, 4, 5, 6 ]; for (index = 0; index < array.length; index++) { console.log(array[index]); } </script> |
Output:
1 2 3 4 5 6
Using while loop.
This is again similar to other languages.
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; while (index < array.length) { console.log(array[index]); index++; }</script> |
Output:
1 2 3 4 5 6
using forEach method.
The forEach method calls the provided function once for every array element in the order.
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); }</script> |
Output:
1 2 3 4 5 6
Using every method.
The every() method checks if all elements in an array pass a test (provided as a function).
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; const under_five = x => x < 5; if (array.every(under_five)) { console.log( 'All are less than 5' ); } else { console.log( 'At least one element is not less than 5' ); } </script> |
Output:
At least one element is not less than 5.
Using map.
A map applies a function over every element and then returns the new array.
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; square = x => Math.pow(x, 2); squares = array.map(square); console.log(array); console.log(squares);</script> |
Output:
1 2 3 4 5 6 1 4 9 16 25 36