How can I loop through all the entries in an array using JavaScript?
- Use for...of loop. See w3schools.com/JS/js_loop_forof.aspuser19690494– user196904942022-08-25 15:28:21 +00:00Commented Aug 25, 2022 at 15:28
- Near duplicate of (but slightly more general than) "Loop through an array in JavaScript".outis– outis2022-10-17 02:15:56 +00:00Commented Oct 17, 2022 at 2:15
- This question is similar to: Loop through an array in JavaScript. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.TylerH– TylerH2025-03-24 13:55:15 +00:00Commented Mar 24 at 13:55
41 Answers
If you have a massive array you should use iterators to gain some efficiency. Iterators are a property of certain JavaScript collections (like Map, Set, String, Array). Even, for..of uses iterator under-the-hood.
Iterators improve efficiency by letting you consume the items in a list one at a time as if they were a stream. What makes an iterator special is how it traverses a collection. Other loops need to load the entire collection up front in order to iterate over it, whereas an iterator only needs to know the current position in the collection.
You access the current item by calling the iterator’s next method. The next method will return the value of the current item and a boolean to indicate when you have reached the end of the collection. The following is an example of creating an iterator from an array.
Transform your regular array to iterator using values() method like this:
const myArr = [2,3,4] let it = myArr.values(); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next()); You can also transform your regular array to iterator using Symbol.iterator like this:
const myArr = [2,3,4] let it = myArr[Symbol.iterator](); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next()); You can also transform your regular array to an iterator like this:
let myArr = [8, 10, 12]; function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {done: true}; } }; }; var it = makeIterator(myArr); console.log(it.next().value); // {value: 8, done: false} console.log(it.next().value); // {value: 10, done: false} console.log(it.next().value); // {value: 12, done: false} console.log(it.next().value); // {value: undefined, done: true} NOTE:
- Iterators are exhaustible in nature.
- Objects are not
iterableby default. Usefor..inin that case because instead of values it works with keys.
You can read more about iteration protocol here.
Comments
You can use:
ForEach
theArray.forEach(function (array, index) { console.log(index); console.log(array); });for
for(var i=0; i<theArray.length; i++) { console.log(i) }map
theArray.map(x => console.log(x));map
theArray.filter(x => console.log(x));
And there are many others for iteration.
Comments
I'd argue that for/of is the way to go:
const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // Prints "a", "b", "c" } Unlike
for/in,for/ofskips non-numeric properties on the array. For example, if you setarr.foo = 'test',for (var v in arr)will loop through the'foo'key.Unlike
forEach(),for/ofdoesn't skip "holes" in arrays.const arr = ['a',, 'c']is valid JavaScript, just the 2nd element is a "hole". The array is functionally equivalent to['a', undefined, 'c'].
You can read more in this blog post on for/of vs forEach().
Comments
Suppose we have an array of subjects:
let ddl = new Array(); if (subjects) { subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});}); } 1 Comment
I come from Python, and I found this way much clearer.
theArray being the array, and instance being the elements of the array:
for (let instance of theArray) { console.log("The instance", instance); } or
for (instance in theArray) { console.log("The instance", instance); } compare to:
theArray.forEach(function(instance) { console.log(instance); }); But at the end of the day both are doing the same thing.
1 Comment
for (instance in theArray) does not do the same as for (let instance of theArray). The former iterates over keys while the latter over values. So if theArray = ["a", "b", "c"] then for..in will print 0, 1, 2 while for..of will print "a", "b", "c"./* Get all forms */ document.querySelectorAll( "form" ).forEach( form => { /* For each form, add the onsubmit event */ form.addEventListener( "submit", event => { event.preventDefault(); // Return false /* Display it */ alert(event.target.action); console.log(event.target); } ); } ); <form action="form1.php" > <input type="submit" value="Submit" /> </form> <form action="form2.php" > <input type="submit" value="Submit" /> </form> <form action="form3.php" > <input type="submit" value="Submit" /> </form> Comments
I do it like this.
foreach
const arr = ["apple", "banana", "orange", "pear", "grape"]; arr.forEach(function(element) { console.log(element); }); for..of
const arr = ["apple", "banana", "orange", "pear", "grape"]; for (const element of arr) { console.log(element); }