Loop Through An Array in JavaScript - Stack Overflow
Loop Through An Array in JavaScript - Stack Overflow
Asked
12 years, 2 months ago Modified
today Viewed
4.8m times
In Java, you can use a for loop to traverse objects in an array as follows:
808
Can I do the same in JavaScript?
6 Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the
objects? And use a sequential one for filling one? Is this correct?
– Mark Szymanski
Jun 10,
2010 at 0:15
51 no, it's really simple, array objects have numeric indexes, so you want to iterate over those
indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop
enumerates object properties, without an specific order, and it also enumerates inherited
properties... for iterating over arrays sequential loops are always recommended...
– Christian C. Salvadó
Jun 10, 2010 at 0:38
6 related - stackoverflow.com/questions/5349425/…
– jondavidjohn
Nov 1, 2011 at 17:53
8 jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays
– EscapeNetscape
Nov 3, 2016 at 19:45
10 @CMS No, it's not really simple. It's really simple in every other language. It's ridiculously
complex in JS, where you have in and of that can both be used and do different things.
Then you also have forEach and the ugly and annoying index based looping. Every other
modern language makes looping over a collection easy and straightforward with no surprises
or confusion. JS could, too, but it doesn't.
– jpmc26
Oct 5, 2018 at 15:59
1 2 Next
Pros
Cons
Too verbose
Imperative
Easy to have off-by-one errors (sometimes also called a fence post error)
2. Array.prototype.forEach :
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
The ES5 specification introduced a lot of beneficial array methods. One of them, the
Array.prototype.forEach , gave us a concise way to iterate over an array:
Being almost ten years as the time of writing that the ES5 specification was released
(Dec. 2009), it has been implemented by nearly all modern engines in the desktop,
server, and mobile environments, so it's safe to use them.
And with the ES6 arrow function syntax, it's even more succinct:
Arrow functions are also widely implemented unless you plan to support ancient
platforms (e.g., Internet Explorer 11); you are also safe to go.
Pros
Declarative
Cons
Normally, you can replace the need to break out of imperative loops by filtering the
array elements before iterating them, for example:
Keep in mind if you are iterating an array to build another array from it, you should use
. I've seentothis
mapOverflow
Join Stack findanti-pattern so many
the best answer times.
to your technical question, help
Sign up
others answer theirs.
Anti-pattern:
console.log(doubled);
Also, if you are trying to reduce the array to a value, for example, you want to sum an
array of numbers, you should use the reduce method.
Anti-pattern:
console.log(sum);
Array objects are by definition built-in iterables in ES6, so you can use this statement
on them:
Pros
Cons
If you are targeting older browsers, the transpiled output might surprise you.
@zipcodeman suggests the use of the for...in statement, but for iterating arrays
for-in should be avoided, that statement is meant to enumerate object properties.
The order of iteration is not guaranteed; the array indexes may not be visited in
numeric order.
The second point is that it can give you a lot of problems, for example, if you extend
the Array.prototype object to include a method there, that property will also be
enumerated.
For example:
Join Stack Overflow to find the best answer to your technical question, help
Array.prototype.foo = "foo!"; Sign up
others answer
vartheirs.
array = ['a', 'b', 'c'];
for (var i in array) {
console.log(array[i]);
}
The above code will console log "a", "b", "c", and "foo!".
That can be particularly a problem if you use some library that relies heavily on native
prototypes augmentation (such as MooTools).
The for-in statement, as I said before, is there to enumerate object properties, for
example:
var obj = {
"a": 1,
"b": 2,
"c": 3
};
In the above example, the hasOwnProperty method allows you to enumerate only own
properties. That's it, only the properties that the object physically has, no inherited
properties.
Enumeration VS Iteration
Share edited May 29, 2021 at 4:15 answered Jun 10, 2010 at 0:07
Improve this answer user229044 ♦ Christian C. Salvadó
Join Stack Overflow to find the best answer to your technical question, help
224k 40 322 333 776k 179Sign910 up 832
Follow theirs.
others answer
6 I know this answer predates async and Promises, but I feel this is worth mentioning in any
conversation pertaining to modern JavaScript: " forEach does not wait for promises. Make
sure you are aware of the implications while using promises (or async functions) as forEach
callback." (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
– bmaupin
Jun 15,
2021 at 11:41
1 I think the mentioned contra of missing "continue" is not really true, just use return inside the
functions, its the equivalent. However, the missing "break" is a valid contra point.
– Adam
May
27 at 5:42
Yes, assuming your implementation includes the for ... of feature introduced in
ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these
1160 days.
(The variable s is different on each iteration, but can still be declared const inside
the loop body as long as it isn't modified there.)
A note on sparse arrays: an array in JavaScript may not actually store as many items as
reported by its length ; that reported number is simply one greater than the highest
Join Stack Overflow to find the best answer to your technical question, help
index attheirs. Sign up by its
which a value is stored. If the array holds fewer elements than indicated
others answer
length, its said to be sparse. For example, it's perfectly legitimate to have an array with
items only at indexes 3, 12, and 247; the length of such an array is reported as 248,
though it is only actually storing 3 values. If you try to access an item at any other
index, the array will appear to have the undefined value there. So when you want to
"loop through" an array, you have a question to answer: do you want to loop over the
full range indicated by its length and process undefined s for any missing elements, or
do you only want to process the elements actually present? There are plenty of
applications for both approaches; it just depends on what you're using the array for.
If you iterate over an array with for .. of , the body of the loop is executed length
times, and the loop control variable is set to undefined for any items not actually
present in the array. Depending on the details of your "do something with" code, that
behavior may be what you want, but if not, you should use a different approach.
Of course, some developers have no choice but to use a different approach anyway,
because for whatever reason they're targeting a version of JavaScript that doesn't yet
support for ... of .
You can of course use an arrow function if your implementation supports ES6+:
myStringArray.forEach( s => {
// ... do something with s ...
} );
Unlike for ... of , .forEach only calls the function for elements that are actually
present in the array. If passed our hypothetical array with three elements and a length
of 248, it will only call the function three times, not 248 times. If this is how you want
to handle sparse arrays, .forEach may be the way to go even if your interpreter
supports for ... of .
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
The final option, which works in all versions of JavaScript, is an explicit counting loop.
You simply count from 0 up to one less than the length and use the counter as an
index. The basic loop looks like this:
One advantage of this approach is that you can choose how to handle sparse arrays.
The above code will run the body of the loop the full length times, with s set to
undefined for any missing elements, just like for .. of ; if you instead want to handle
only the actually-present elements of a sparse array, like .forEach , you can add a
simple in test on the index:
The explicit counting loop also means you have access to the index of each value,
should you want it. The index is also passed as an extra parameter to the function you
pass to forEach , so you can access it that way as well:
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 is it guaranteed to iterate over those in numeric order. Therefore, the for ... in
syntax should not be used for looping through Arrays.
22 Note that some interpreters (e.g. V8) will automatically cache the length of the array if the
code is called enough times and it detects that the length is not modified by the loop. While
caching the length is still nice, it may not provide a speed boost when your code is being
invoked enough times to actually make a difference.
– Phrogz
Jun 4, 2012 at 16:29
You can use map , which is a functional programming technique that's also available in
other languages like Python and Haskell.
452
[1,2,3,4].map( function(item) {
alert(item);
})
array.map(func)
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
In general func would take one parameter, which is an item of the array. But in the
case of JavaScript, it can take a second parameter which is the item's index, and a third
parameter which is the array itself.
The return value of array.map is another array, so you can use it like this:
You don't have to write the function inline. It could be a separate function.
new_list = my_list.map(item_processor);
Share Improve this answer edited Feb 6, 2018 at 3:40 answered Jun 10, 2010 at 0:09
Follow Peter Mortensen hasen
30.2k 21 100 124 156k 64 188 228
103 That particular example is probably better implemented using Array.forEach . map is for
generating a new array.
– harto
Jun 10, 2010 at 0:20
21 @hasen, the Array.prototype.map method is part of the ECMAScript 5th Edition Standard,
is not yet available on all implementations (e.g. IE lacks of it), also for iterating over an array I
think the Array.prototype.forEach method is more semantically correct... also please
don't suggest the for-in statement, see my answer for more details :)
– Christian C. Salvadó
Jun 10, 2010 at 0:30
forOverflow
Join Stack (consttosfind
ofthemyStringArray) { question, help
best answer to your technical
Sign up
others answer theirs.
141 (Directly answering your question: now you can!)
Most other answers are right, but they do not mention (as of this writing) that
ECMAScript 6 2015 is bringing a new mechanism for doing iteration, the for..of
loop.
This new syntax is the most elegant way to iterate an array in JavaScript (as long you
don't need the iteration index).
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with
other browsers (see browser compatibility below). Luckily we have JavaScript compilers
(such as Babel) that allow us to use next-generation features today.
Iterating an array
// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
const band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
Iterating a generator:
Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops
Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
Share Improve this answer edited Apr 2 at 8:49 answered Aug 11, 2013 at 15:54
Follow tagurit Marlon Bernardes
445 5 12 12.5k 7 36 44
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's
better to use a for loop such as:
130
for(var i=0, len=myArray.length; i < len; i++){}
It's optimized as well ("caching" the array length). If you'd like to learn more, read my
post on the subject.
Share Improve this answer edited Jan 22 at 8:28 answered Dec 7, 2010 at 7:24
Follow Josh DeLong sebarmeli
461 5 23 17.7k 7 33 40
Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for
optimizing many common loops.
93
You may not need all of them, but they can be very useful, or would be if every browser
supported
Join Stack them.
Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
Mozilla Labs published the algorithms they and WebKit both use, so that you can add
them yourself.
forEach runs a function on each array member and doesn't return anything.
map is like forEach, but it returns an array of the results of the operation for each
element.
These methods all take a function for their first argument and have an optional second
argument, which is an object whose scope you want to impose on the array members
as they loop through the function.
indexOf and lastIndexOf find the appropriate position of the first or last element that
matches its argument exactly.
(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
Join Stack Overflow to find the best answer to your technical question, help
} Sign up
others answer theirs.
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
Join Stack Overflow to find the(i<L){
while best answer to your technical question, help
Sign up
others answer theirs. if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();
Share Improve this answer edited Jul 2, 2016 at 19:57 answered Jun 10, 2010 at 2:43
Follow Peter Mortensen kennebec
30.2k 21 100 124 99.6k 31 103 125
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
console.log(element);
});
3. Using for...of
for...of loop gives you direct access to the array elements.
Join Stacklet
Overflow
array =to[find
1, 2the
, 3,best
4, answer
5]; to your technical question, help
Sign up
others answer
let theirs.
length = array.length;
while(length > 0){
console.log(array[array.length - length]);
length--;
}
Share Improve this answer edited Apr 10 at 11:06 answered Jun 5, 2021 at 6:21
Follow Martijn Pieters ♦ Satish Chandra Gupta
975k 270 3844 2,290 18 22
3207
Introduction
Since my time in college, I've programmed in Java, JavaScript, Pascal, ABAP, PHP,
83
Progress 4GL, C/C++ and possibly a few other languages I can't think of right now.
While they all have their own linguistic idiosyncrasies, each of these languages share
many of the same basic concepts. Such concepts include procedures / functions, IF -
statements, FOR -loops, and WHILE -loops.
2. The condition: checks a condition every time before the loop block is executed,
and quits the loop if false
3. The afterthought: performed every time after the loop block is executed
These three components are separated from each other by a ; symbol. Content for
each of these three components is optional, which means that the following is the most
minimal for loop possible:
for (;;) {
// Do stuff
}
Usually, though, the initialization is used to declare an index, the condition is used to
compare that index with a minimum or maximum value, and the afterthought is used
to increment the index:
Whichever works best is largely a matter of both personal taste and the specific use
case you're implementing.
Note that each of these variations is supported by all browsers, including very very old
ones!
A while loop
One alternative to a for loop is a while loop. To loop through an array, you could do
this:
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Like traditional for loops, while loops are supported by even the oldest of browsers.
Also, note that every while loop can be rewritten as a for loop. For example, the
while loop hereabove behaves the exact same way as this for -loop:
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
for(var key = 0; value = myArray[key++];){
console.log(value);
}
for (i in myArray) {
console.log(myArray[i]);
}
This should be used with care, however, as it doesn't behave the same as a traditional
for loop in all cases, and there are potential side-effects that need to be considered.
See Why is using "for...in" for array iteration a bad idea? for more details.
As an alternative to for...in , there's now also for for...of . The following example
shows the difference between a for...of loop and a for...in loop:
Array.prototype.forEach()
Libraries
Finally, many utility libraries also have their own foreach variation. AFAIK, the three
most popular ones are these:
jQuery.each() , in jQuery:
_.each() , in Underscore.js:
_.forEach() , in Lodash:
Share Improve this answer edited Oct 30, 2020 at 8:20 answered Feb 29, 2016 at 18:56
It logs: 'one','two','three'
Share Improve this answer edited Oct 30, 2020 at 6:59 answered Jan 5, 2012 at 9:15
Follow Peter Mortensen Timo Huovinen
30.2k 21 100 124 50.5k 33 141 133
21 The first example of the "while" syntax won't work if any of the array elements is falsy.
– Chris Cooper
Apr 16, 2012 at 14:42
2 ... and this while loop is equivalent to: for (var i=0,item; item=items[i]; i++) , which takes away
the need to declare the index and item variables beforehand...
– Stijn de Witt
Mar 31, 2013 at
19:09
If you want a terse way to write a fast loop and you can iterate in reverse:
This has the benefit of caching the length (similar to for (var i=0,
len=myArray.length; i<len; ++i) and unlike for (var i=0; i<myArray.length; ++i) )
while being fewer characters to type.
Join Stack
ThereOverflow
are evento find times
some the best answer
when youto your to
ought technical
iterate question, help
in reverse, such as when
Sign upiterating
others answer theirs.
over a live NodeList where you plan on removing items from the DOM during iteration.
Share Improve this answer edited Dec 22, 2015 at 17:16 answered Jun 4, 2012 at 16:26
Follow falsarella Phrogz
12.1k 8 69 113 287k 105 636 725
16 For the people that don't get what is so ingenious: The i-- expression is first evaluated and
allows the loop to continue when it's not falsish... Afterwards the counter is decremented. As
soon as i becomes zero it will break out of the loop as zero is a falsish value in Javascript.
– Stijn de Witt
Mar 1, 2013 at 12:09
5 falsish? You mean falsey. Let's all stick the proper terminology to avoid confusion ;)
– danwellman
Apr 27, 2013 at 7:33
Some use cases of looping through an array in the functional programming way in
JavaScript:
39
1. Just loop through an array
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
Join Stack Overflow to find the best answer to your technical question, help
3. Transform to a new array Sign up
others answer theirs.
const myArray = [{x:100}, {x:200}, {x:300}];
Note: The map() method creates a new array with the results of calling a provided
function on every element in the calling array.
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
console.log(groupInfo); // {A: 3, C: 1, B: 2}
Note: The filter() method creates a new array with all elements that pass the test
implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
console.log(sortByAge);
The Array.prototype.find() method returns the value of the first element in the array
that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
Share Improve this answer edited Jul 29, 2018 at 10:36 answered Feb 23, 2018 at 11:29
Follow Yuci
23.7k 8 100 109
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are
many ways to do a loop over arrays in JavaScript. Imagine you have this array below,
37 and you'd like to do a loop over it:
1) For loop
Join Stack Overflow to find the best answer to your technical question, help
for (var i=0, l=arr.length; i<l; i++) { Sign up
others answer theirs.
console .log(arr[i]);
}
2) While loop
A while loop is considered as the fastest way to loop through long arrays, but it is
usually less used in the JavaScript code:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
A do while is doing the same thing as while with some syntax difference as below:
let i=0;
do {
console.log(arr[i]);
i++;
}
while (arr.length>i);
These are the main ways to do JavaScript loops, but there are a few more ways to do
that.
Also look at the map() , filter() , reduce() , etc. functions on an Array in JavaScript.
They may do things much faster and better than using while and for .
This is a good article if you like to learn more about the asynchronous functions over
arrays in JavaScript.
This article will take a close look at what I like to call the "big
three" list
operations: map, filter, and reduce. Wrapping your head
around these three
functions is an important step towards being able
to write clean functional
code, and opens the doors to the vastly
powerful techniques of functional and
reactive programming.
Share Improve this answer edited Oct 30, 2020 at 8:26 answered May 27, 2017 at 2:57
Follow Peter Mortensen Alireza
30.2k 21 100 124 94.6k 25 262 165
There is a way to do it where you have very little implicit scope in your loop and do
away with extra variables.
31
var i = 0,
item;
Or if you really want to get the id and have a really classical for loop:
var i = 0,
len = myStringArray.length; // Cache the length
Modern browsers all support iterator methods forEach , map , reduce , filter and a
host Overflow
Join Stack of other methods onbest
to find the the answer
Array prototype .
to your technical question, help
Sign up
others answer theirs.
dM 16 2011 22 52
Share Improve this answer edited Oct 30, 2020 at 6:57 answered May 16, 2011 at 22:52
3 Note that some interpreters (e.g. V8) will automatically cache the length of the array if the code
is called enough times and it detects that the length is not modified by the loop.
– Phrogz
Jun
4, 2012 at 16:28
Thanks for the info @Phrogz it's true that there is a lot of optimizations that the VM can make,
but since older browsers don't have this it would still be best practice to optimize for it since it
is so cheap.
– Gabriel
Jun 26, 2012 at 1:43
1 @Gabriel: Why? Please give real-world examples showing that not caching the length is actually
a performance bottleneck. I follow the 'premature optimization is the root of all evil' approach. I
will fix that one loop that actually poses a problem once I encounter it...
– Stijn de Witt
Mar 31,
2013 at 19:06
1 @StijndeWitt imo it is just a stylistic issue. Honestly I no longer even use for loops instead
relying on underscore for things like _.each, _.map etc. to do these things. When I did write
loops like this I cached the length primarily so that all my variable declaration were in one
place, at the top of my function. Following my advice in this regard is inconsequential to any
real world application. Premature optimization is super bad, but if optimization happens to
result from stylistic decisions I don't think it actually matters.
– Gabriel
Apr 4, 2013 at 17:15
1 @Gabriel I believe JavaScript already supports the map function on arrays, no need to
introduce an additional lib for that.
– Noz
Jul 30, 2014 at 18:14
29 Generic loop:
var i;
for (i = 0; i < substr.length; ++i) {
// Do something with `substr[i]`
}
ES5's forEach:
substr.forEach(function(item) {
// Do something with `item`
});
Join Stack Overflow to find the best answer to your technical question, help
jQuery.each: Sign up
others answer theirs.
jQuery.each(substr, function(index, item) {
// Do something with `item` (or `this` is also `item` if you like)
});
Have a look this for detailed information or you can also check MDN for looping
through an array in JavaScript & using jQuery check jQuery for each.
Share Improve this answer edited May 23, 2017 at 10:31 answered Jul 23, 2014 at 12:59
Follow Community Bot RizN81
1 1 999 14 25
Array loop:
Object loop:
Share Improve this answer edited May 21, 2017 at 11:05 answered Aug 1, 2016 at 21:18
Follow Peter Mortensen bzim
30.2k 21 100 124 1,002 9 17
I would thoroughly recommend making use of the Underscore.js library. It provides you
with various functions that you can use to iterate over arrays/collections.
29
For instance:
7 For new discoverers of this question, I'd just like to point out Lo-Dash, a spiritual successor of
Underscore's that improves upon it in many ways.
– Mark Reed
Oct 11, 2013 at 10:59
3 Why use underscore if ECMA-262 has been added the forEach methor. The native code is
always better.
– Walter Chapilliquen - wZVanG
Jun 23, 2015 at 23:32
Results:
The traditional for() iterator, is by far the fastest method, especially when used with
the array length cached.
Join Stack Overflow to find the best answer to your technical question, help
let arr = [1,2,3,4,5]; Sign up
others answer theirs.
for(let i=0, size=arr.length; i<size; i++){
// Do something
}
Share Improve this answer edited Sep 28, 2019 at 21:55 answered Aug 20, 2018 at 23:36
Follow Peter Mortensen colxi
30.2k 21 100 124 6,615 2 41 40
2 Could be improved: Please use: ++i instead of i++, this will avoid an temporary object. So it
reduces memory usage and cpu time (no allocation required)!
– PowerStat
May 17, 2019 at
10:05
@PowerStat can you provide a link or reference about that ? I've never aheard about it, sounds
interesting...
– colxi
May 17, 2019 at 13:23
1 @colxi For such interesting things you should read the hardcore C++ stuff from Herb Sutter
and Scott Meyers. The ++i vs i++ thing is from the book: Exceptional C++: 47 Engineering
Puzzles, Programming Problems, and Solutions - I thing you could also find it on gotw.ca but
can be proved for every programing language.
– PowerStat
May 17, 2019 at 17:44
I did not yet see this variation, which I personally like the best:
22 Given an array:
You can loop over it without ever accessing the length property:
Also, as CMS mentions in a comment below, you can only use this on arrays that don't
contain any falsish values. The array of strings from the example works, but if you have
empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely.
Again in practice this is hardly ever a problem for me, but it is something to keep in
mind, which makes this a loop to think about before you use it... That may disqualify it
for some people :)
Combines very naturally with array.push and array.splice to use arrays like
lists/stacks
The reason this works is that the array specification mandates that when you read an
item from an index >= the array's length, it will return undefined. When you write to
such a location it will actually update the length.
For me, this construct most closely emulates the Java 5 syntax that I love:
... with the added benefit of also knowing about the current index inside the loop
Share Improve this answer edited Sep 28, 2019 at 22:14 answered Feb 28, 2013 at 13:59
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others14 Notice
answer that with this approach the loop will stop as soon it finds a falsey value, such as an
theirs.
empty string, 0 , false , NaN , null or undefined , even before i reaches the length,
empty string, 0 , false , NaN , null or undefined , even before i reaches the length,
e.g.: jsfiddle.net/prvzk/1
– Christian C. Salvadó
Feb 28, 2013 at 18:31
Returns: Object
Share Improve this answer edited Dec 22, 2015 at 17:12 answered Oct 21, 2012 at 6:20
Follow falsarella justingordon
12.1k 8 69 113 12.2k 11 66 115
6 Agreed with Exception. Do not underestimate the impact of extra dependencies. I would advice
against this except in code that is already heavily using jQuery anyway.
– Stijn de Witt
Mar 31,
2013 at 19:04
2 Update: These days, you can use Array.forEach to get much of the same effect with native
arrays.
– Stijn de Witt
Jun 5, 2017 at 10:50
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
There are 4 ways of array iteration:
21
// 1: for
// 2: forEach
// 3: for in
// 4: for of
Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The
best way is 4th - "for of".
Share Improve this answer edited Aug 1, 2021 at 17:29 answered Jun 15, 2021 at 14:03
Follow Aleksandr Golovatyi
943 1 10 16
2 do you care to elaborate why 4 "for of" is the best over the others
– YesItsMe
Aug 3, 2021 at
2:04
It doesn't create needless variables or function context. But if you don't care about small
disadvantages you can use any of them, what is more comfortable for you. @YesItsMe Thank
you for the question.
– Aleksandr Golovatyi
Aug 3, 2021 at 9:39
20
let a= ["Hello", "World"];
Share Improve this answer edited Mar 1, 2021 at 5:17 answered Dec 19, 2019 at 6:40
Follow Kamil Kiełczewski
73.5k 26 334 303
that's the Haskell-y way to do it; keep taking the first one. clever, but probably slow.
– Sapphire_Brick
Jan 16, 2020 at 2:49
4 You have make a good point. I ran your example with an array of 1000 items, and
while(a.length) { console.log(a.shift()); } was about twice as fast as the for(var
i = 0; i < a.length; i++) { console.log(a[i]); } version. ¯\_(ツ)_/¯
– Sapphire_Brick
Aug 4, 2020 at 20:51
3 Even if it does not exist in your native language, you should not leave out articles in English (the
indefinite article ("a" or "an") and the definite article ("the")). See e.g. English Articles - 3 Simple
Rules To Fix Common Grammar Mistakes & Errors and A, AN, THE - Articles in English.
– Peter Mortensen
Oct 30, 2020 at 8:35
2 @Pitouli you are right - I rollback answer to its initial form. When I have more time then I will
perform benchamarks again
– Kamil Kiełczewski
Mar 1, 2021 at 5:21
There's a method to iterate over only own object properties, not including prototype's
ones:
19
for (var i in array) if (array.hasOwnProperty(i)) {
// Do something with array[i]
}
In JavaScript any custom property could be assigned to any object, including an array.
If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if
(i in array) or array.forEach with es5shim should be used.
Share Improve this answer edited Sep 28, 2019 at 22:15 answered Apr 15, 2012 at 12:50
Join Stack Overflow to find the best answer
Follow toMortensen
Peter your technical question, help
kirilloid
Sign up
others answer theirs. 30.2k 21 100 124 13.5k 6 37 52
And how about using for (var i in array) if (++i) ?
– Daniel Sokolowski
Oct 9, 2014
at 14:40
http://jsperf.com/native-loop-performance/8
Comparing methods for looping through an array of 100000 items and do a minimal
operation with the new value each time.
http://jsben.ch/#/BQhED
Preparation:
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-
min.js"></script>
<script>
Benchmark.prototype.setup = function() {
// Fake function with minimal action on the value
var tmp = 0;
var process = function(value) {
tmp = value; // Hold a reference to the variable (prevent engine
optimisation?)
};
Share Improve this answer edited Jun 20, 2020 at 9:12 answered Mar 8, 2014 at 2:06
Follow Community Bot molokoloco
1 1 4,326 2 31 27
My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-
performance/16
– molokoloco
Mar 27, 2014 at 16:41
@bergi is right. This loop wipes out the array as it loops through it. Not what you want in most
cases.
– Stijn de Witt
May 15, 2014 at 17:34
There are a couple of ways to do it in JavaScript. The first two examples are JavaScript
samples. The third one makes use of a JavaScript library, that is, jQuery making use of
14 the .each() function.
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
var myStringArray = ["hello", "World"];
$.each(myStringArray, function(index, value){
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Share Improve this answer edited Jul 2, 2016 at 19:37 answered Apr 21, 2016 at 16:03
Follow Peter Mortensen Shubham Khatri
30.2k 21 100 124 251k 52 374 376
The optimized approach is to cache the length of array and using the single variable
pattern, initializing all variables with a single var keyword.
14
var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
// Do something
}
If the order of iteration does not matter then you should try reversed loop. It is the
fastest as it reduces overhead condition testing and decrement is in one statement:
Join Stack Overflow to find the best answer to your technical question, help
var myStringArray = ["item1","item2"],i = myStringArray.length; Sign up
others answer theirs.
while(i--) {
// Do something with fruits[i]
}
Share Improve this answer edited Oct 30, 2020 at 8:16 answered Jan 11, 2014 at 20:53
Follow Peter Mortensen Zaheer Ahmed
30.2k 21 100 124 27.6k 11 73 109
console.log()
console.log()
let i = 0
while (i < items.length) {
console.log(items[i++])
}
console.log()
console.log()
items.forEach(item => {
console.log(item)
})
console.log()
console.log()
console.log()
console.log()
Share Improve this answer edited May 21, 2017 at 11:05 answered Oct 14, 2016 at 10:31
Follow Peter Mortensen Alongkorn
30.2k 21 100 124 user 3,474 1 23 41
Share Improve this answer edited Mar 17, 2018 at 0:41 answered Mar 30, 2016 at 2:37
Follow Redoman
2,703 2 32 61
The best way in my opinion is to use the Array.forEach function. If you cannot use that I
would suggest to get the polyfill from MDN. To make it available, it is certainly the
13 safest way to iterate over an array in JavaScript.
Array.prototype.forEach()
This ensures
Join Stack Overflow that anything
to find youanswer
the best need in
tothe
yourscope of processing
technical the array stays within
question, help
Sign up
othersthat
answer theirs.
scope, and that you are only processing the values of the array, not the object
properties and other members, which is what for .. in does.
Using a regular C-style for loop works in most cases. It is just important to remember
that everything within the loop shares its scope with the rest of your program, the { }
does not create a new scope.
Hence:
var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
alert(i);
will output "11" - which may or may not be what you want.
Share Improve this answer edited Sep 28, 2019 at 22:08 answered Oct 26, 2016 at 8:51
Follow Peter Mortensen Espen
30.2k 21 100 124 user 2,370 1 14 23
12
var myStringArray = ['Hello', 'World']; // The array uses [] not {}
for (var i in myStringArray) {
console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not
the item
}
Share Improve this answer edited Oct 30, 2020 at 7:00 answered Apr 18, 2012 at 14:46
Follow Peter Mortensen Muhammad Alvin
30.2k 21 100 124 1,150 9 9
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.
1 It seems that this would run up against similar problems as other for in usages with an array
p g p g y
object, in that prototype member variables would be caught by the for in as well.
– Kzqai
Apr
18, 2012 at 15:34
11 [].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>
Share Improve this answer edited Aug 24, 2020 at 17:51 answered Oct 21, 2014 at 7:32
Follow Joter
306 2 5
1 2 Next
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer
this question. The reputation requirement helps protect this question from spam and non-answer
activity.
Join Stack Overflow to find the best answer to your technical question, help
Sign up
others answer theirs.