1. Introduction
In this short article, we are going to present several ways to iterate through an array in JavaScript.
2. Using sequential for loop
To loop through array in JavaScript we can use simple function
for
and
lenght
attribute - to get the size of the array. The following snippets shows how to use it:
var array = ["a", "b", "c", "d"];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
3. Using forEach
function
JavaScript
forEach
function was introduction in version
ECMAScript 5
.
forEach
can be used to execute a function on each item in the array. Check the following example, where we print every item of the array with index:
const array = ["a", "b", "c", "d"];
array.forEach((item, index) => console.log(index, item));
4. Using for-of
statement
The
for-of
statement creates a loop iterating over iterable objects like array.
const array = ["a", "b", "c", "d"];
for (const item of array){
console.log(item);
}
5. Conclusion
In this article, we presented several ways to iterate over the array in JavaScript.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}