@kabirbaidhya 2020-09-21 15:42:45

Array traversal cheatsheet in JavaScript

Given an array, you can traverse it one of the many ways as follows.

1. Classic for loop

const myArray = ['Hello', 'World'];

for (let i = 0; i < myArray.length; i++) {

2. for...of

const myArray = ['Hello', 'World'];

for (const item of myArray) {

3. Array.prototype.forEach()

const myArray = ['Hello', 'World'];

myArray.forEach(item => {

4. while loop

const myArray = ['Hello', 'World'];
let i = 0;

while (i < myArray.length) {

5. do...while loop

const myArray = ['Hello', 'World'];
let i = 0;

do {
} while (i < myArray.length);

6. Queue style

const myArray = ['Hello', 'World'];

while (myArray.length) {

7. Stack style

Note: The list is printed reverse in this one.

const myArray = ['Hello', 'World'];

while (myArray.length) {

@victorq10 2014-10-21 07:32:00

For example, I used in a Firefox console:

[].forEach.call(document.getElementsByTagName('pre'), function(e){ 

You can use querySelectorAll to get same result

document.querySelectorAll('pre').forEach( (e) => { 
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

@Kamil Kiełczewski 2019-12-19 06:40:09

Esoteric but fast

let a= ["Hello", "World"];

while(a.length) { console.log( a.shift() ); }

Performance test

Today (2020-08-05) I perform test on Chrome 84, Safari 13 and Firefox 78 on chosen solutions.


  • while solution (A) is fastest on all browser for all arrays except big one on Chrome (which is surprising).
  • for medium arrays while solution (A) is thousands of times faster than other solutions (!!!)
  • while solution (A) slows down on chrome for arrays witch 30-40k elements
  • for-in solution (B) is slowest


enter image description here


I perform 3 tests:

  • small - for 2 elements array (like OP) - you can run it here
  • medium - for 10K elements array and - you can run it here
  • big - for 100K elements array - you can run it here

Below snippet presents code used in test

function A(a) {
  let r=0;
  while(a.length) r+= a.shift().length;
  return r;

function B(a) {
  let r=0;
  for(i in a) r+= a[i].length;
  return r;

function C(a) {
  let r=0;
  for(x of a) r+= x.length;
  return r;

function D(a) {
  let r=0;
  for (i=0; i<a.length; ++i) r+= a[i].length;
  return r;


function E(a) {
  let r=0;
  a.forEach(x=> r+= x.length);
  return r;

let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))

Here are example results for Chrome for medium array

enter image description here

@Sapphire_Brick 2020-01-16 02:49:07

that's the Haskell-y way to do it; keep taking the first one. clever, but probably slow.

@Kamil Kiełczewski 2020-07-24 10:06:40

@Sapphire_Brick actually it is quite fast - here is test

@Sapphire_Brick 2020-07-24 21:24:20

Of course a simple program like this is fast, but how does it scale in comparison to for(...;...;...) or for(... of ...)?

@Kamil Kiełczewski 2020-07-24 22:04:16

@Sapphire_Brick don't be lazy! :) you can check it your self- I give you link (test) to tool in above comment. However for small array case (as OP uses) when you need to optimize speed you should choose solution fastest for small arrays (not for big arrays - which can be different)

@Sapphire_Brick 2020-08-04 20:51:53

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. ¯\_(ツ)_/¯

@Kamil Kiełczewski 2020-08-04 21:23:16

@Sapphire_Brick - thank you for your comment - I tink using console.log in tests is not good because it is complex system function and have big impact on run time. I check with r+=a[i].length (sum of words length) for array witch 1000 elements - and still this solution was much faster than other solution (and probaly the speed difference grow when number of elements grow...) - I'm surprised too that this solution is so fast :)

@Marlon Bernardes 2013-08-11 15:54:05

for (const s of myStringArray) {

(Directly answering your question: now you can!)

Most other answers are right, but they do not mention (as of this writing) that ECMA Script  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 JS compilers (such as Babel) that allow us to use next-generation features today.

It also works on Node (I tested it on version 0.12.0).

Iterating an array

// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) { 

Iterating an array of objects

const band = [
  {firstName : 'John', lastName: 'Lennon'}, 
  {firstName : 'Paul', lastName: 'McCartney'}

for(const member of band){
  console.log(member.firstName + ' ' + member.lastName); 

Iterating a generator:

(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)

function* fibonacci() { // a generator function
  let [prev, curr] = [1, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;

for (const n of fibonacci()) {
  // truncate the sequence at 1000
  if (n >= 1000) {

Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops

Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators


@joeytwiddle 2018-02-10 06:26:01

If you're using ES6, I would suggest const s instead of var s

@theferrit32 2019-05-04 04:46:25

In my tests on large arrays, using var s of arr is almost double (1.9x) the execution time compared to using a simple counter for-loop and retrieving elements by index in nodejs

@Peter Mortensen 2019-09-28 22:12:16

Why that weird stuff in the first and last line?

@Christian C. Salvadó 2010-06-10 00:07:12

You have several options:

1. Sequential for loop:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    //Do something


  • Works on every environment
  • You can use break and continue flow control statements


  • Too verbose
  • Imperative
  • Easy to have off-by-one errors (sometimes also called a fence post error)

2. Array.prototype.forEach

The ES5 specification introduced a lot of beneficial array methods, one of them, the Array.prototype.forEach and it gives us a concise way to iterate over an array:

const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);

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:

array.forEach(item => console.log(item));

Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., IE11); you are also safe to go.


  • Very short and succinct.
  • Declarative


  • Cannot use break / continue

Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

Keep in mind if you are iterating an array to build another array from it, you should use map, I've seen this anti-pattern so many times.


const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

Proper use case of map:

const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);


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.


const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

Proper use of reduce:

const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);


3. ES6 for-of statement

The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.

This statement works for any kind of iterable object and also for generators (any object that has a [Symbol.iterator] property).

Array objects are by definition built-in iterables in ES6, so you can use this statement on them:

let colors = ['red', 'green', 'blue'];
for (const color of colors){


  • It can iterate over a large variety of objects.
  • Can use normal flow control statements (break / continue).
  • Useful to iterate serially asynchronous values.


Do not use for...in

@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.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed; the array indexes may not be visited in numeric order.
  • Inherited properties are also enumerated.

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:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {

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

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) { 
        // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
        console.log("prop: " + prop + " value: " + obj[prop])

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.

I would recommend you to read the following article:

@OscarRyz 2010-06-10 00:13:31

This is the reason ( by CMS him self ) stackoverflow.com/questions/1885317/…

@Shelby Moore III 2012-02-08 09:03:41

Yours enumerates undefined elements, and for(in) doesn't. Official foreach algorithm checks if(in). I agree that iterating only numeric indices is correct for element enumeration (hasOwnProperty will allow non-numeric properties), note it is superior design to not depend on iteration order, so as to enable parallelism, assuming the iterated callback doesn't have side-effects.

@Gras Double 2012-04-17 18:41:30

@Gabriel and @YuriKolovsky are right, accessing the length property has some cost in JS and you should always cache it, like so: for (var i = 0, l = myStringArray.length; i < l; i++) { ... }

@Matthijs Wessels 2012-08-14 16:41:30

@DoubleGras, I think that is an opinion that is not shared by everyone. See: stackoverflow.com/questions/5752906/… or groups.google.com/forum/?fromgroups#!topic/jsmentors/…

@Stijn de Witt 2013-02-28 14:03:14

Anyone thinking you need to cache the length... Please see my answer, you don't even need to access it a single time, let alone cache it: for (var i=0, item; item=myStringArray[i]; i++) { /* use item here */ }

@Phrogz 2013-04-27 13:32:43

@StijndeWitt No, because that breaks if you have any "falsey" values in your array: false, undefined, 0, "", NaN.

@Enrico 2013-08-07 07:26:21

jsperf.com/caching-array-length/4 Here is a test to see if it is worth caching the length of an array in a Javascript loop

@jasop 2013-08-16 01:35:13

Enrico's link to a performance comparison between caching and not caching shows that 'not caching' is.... 0.02% slower! negligible really

@techie_28 2013-08-20 08:39:13

Can I add something to JS array while iterating over it?Will that add on to the iterations?

@Timo Huovinen 2013-09-23 18:04:57

The only reason I can think of for not caching the length is if the array changes while the loop is in progress

@DanielST 2014-09-10 13:57:44

I understand that for...in loops are undesirable for arrays but forEach is a viable alternative a lot of the time. It looks cleaner, encourages code seperation and reuse, and is supported by IE9+ (EMCA 5.1 standard). It would be really nice if it was edited into this answer as an alternative approach.

@Alex Couper 2015-11-27 19:17:47

In ES6 you can do: for (let i of arr) { } See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@4castle 2016-06-16 19:58:32

Another reason not to use for..in with an array, the counter variable will be a STRING!!

@nanomosfet 2018-10-29 23:47:03

For those of you saying not to use for..in consider for..of It seems MDN endorses this for Arrays developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@Mohammed Shareef C 2019-07-09 11:16:39

The transpiled output for for-ofis awful. In that case, it think the conventional for loop is better

@Christian C. Salvadó 2019-07-09 11:59:21

@MohammedShareefC, yes, if there's no type inference, the output is enormous; this is because for-of can work with any iterable. However, if you are dealing with an array, Babel is smart enough to output a conventional for loop. Check this out. Also keep in mind that it is just a matter of time, in some years, we won't need to transpile that... Cheers!

@John Slegers 2016-02-29 18:56:30


Since my time in college, I've programmed in Java, JavaScript, Pascal, ABAP, PHP, 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.

A traditional for-loop

A traditional for loop has three components:

  1. The initialization: executed before the look block is executed the first time
  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

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

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:

for (var i = 0, length = 10; i < length; i++) {

Using a traditional for loop to loop through an array

The traditional way to loop through an array, is this:

for (var i = 0, length = myArray.length; i < length; i++) {

Or, if you prefer to loop backwards, you do this:

for (var i = myArray.length - 1; i > -1; i--) {

There are, however, many variations possible, like for example this one:

for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {

...or this one...

var i = 0, length = myArray.length;
for (; i < length;) {

...or this one:

var key = 0, value;
for (; value = myArray[key++];){

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++]){

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:

for(var key = 0; value = myArray[key++];){

For...in and for...of

In JavaScript, you can also do this:

for (i in myArray) {

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" with 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:

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7

Additionally, you need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least Internet Explorer 10.


An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:

myArray.forEach(function(value, key, myArray) {

Array.prototype.forEach() is supported by all modern browsers, as well as Internet Explorer 9 and later.


Finally, many utility libraries also have their own foreach variation. AFAIK, the three most popular ones are these:

jQuery.each(), in jQuery:

$.each(myArray, function(key, value) {

_.each(), in Underscore.js:

_.each(myArray, function(value, key, myArray) {

_.forEach(), in Lodash.js:

_.forEach(myArray, function(value, key) {

@Sapphire_Brick 2019-08-15 00:50:09

You can either use Array.prototype.forEach(...):

var arr = ["apple", "banana", "cherry", "mango"];
arr.forEach((item, index)=>{
   //Some code...

Or Array.prototype.map(...):

var arr = ["apple", "banana", "cherry", "mango"];
arr.map((item, index)=>{
   //Some code...

Or the jquery or for loop ways previously mentioned.

@Mark Reed 2012-04-16 02:03:36

Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.

It works like this:

var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
  // ... do something with s ...

Or better yet, since ECMAScript 2015 also provides block-scoped variables:

const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
  // ... do something with s ...
// s is no longer defined here

(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 index at which a value is stored. If the array holds fewer elements than indicated by its 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 undefineds 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.

As long as your JavaScript implementation 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 Array#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 ...
} );

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. It also distinguishes between missing elements and elements that are actually set to undefined; for the latter, it will still call the function, passing undefined as the argument. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.

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:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  s = myStringArray[i];
  // ... do something with s ...

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:

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 may 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 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:

myStringArray.forEach( function(s, i) {
   // ... do something with s and i ...

for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an Array (for..of works for other iterable types which may not have this method), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:

for (const [i, s] of myStringArray.entries()) {
  // ... do something with s and 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 is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.

@Phrogz 2012-06-04 16:29:24

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.

@Denis V 2013-11-28 21:08:37

@mark-reed Could you please explain why you used i in myStringArray in your example? How can that be false?

@Mark Reed 2013-11-28 23:40:37

@DenisV - easily - the array could be sparse. The fact that a.length == n only means that the highest numeric key in the array is n-1 - it doesn't necessarily imply that the rest of the keys 0 through n-2 are actually present in the array. That's the typical case, but it's not by any means guaranteed.

@Denis V 2013-11-29 11:59:25

@MarkReed I would say, it's not true. You cannot delete an array element without changing the length property. length property guarantees that you have length elements in the array. Arrays always have all the IDs (though elements can be undefined). And the only way you can delete an item from the Array is splice and it renumbers the items and changes the length. While delete a[i] preserves the id, but assigns the value of this element to undefined.

@Mark Reed 2013-11-29 13:34:36

@DenisV: false. a=[1,2,3,4]; delete a[2]; for (j in a) { console.log(j); } outputs 0, 1, 3, and 4. a.length is still 5.

@Denis V 2013-11-29 14:30:19

@MarkReed but doing for j in a for Array is highly discouraged. And if you access non-existing element in an array, it will not throw an error or produce any other unexpected behavior.

@Denis V 2013-11-29 14:32:43

@MarkReed moreover, if you use console.log(a) you will get the following: [1, 2, undefined, 4], which proves that the 3rd element exists. I agree, that it looks like inconsistency in the standard, but I believe, the check is reduntant in this case.

@Mark Reed 2013-11-30 01:14:07

I'm not suggesting for j in a. I'm demonstrating that the in check is not redundant, as you claimed it was, by showing all the indexes and showing that there is one between 0 and length-1 that is not there. I could also have just printed 2 in a, which is indeed false, despite the fact that you said that was impossible.

@Grijesh Chauhan 2014-01-14 15:37:58

As you says that "restrict yourself to a subset of available JavaScript engines" Is it means forEach is not available in all browsers? Btw your answer is very helpful to me Thanks!

@Mark Reed 2014-01-14 15:40:39

@GrijeshChauhan - correct. For instance, IE through version 8 doesn't support it. See this question.

@Codebling 2014-09-05 07:42:47

@MarkReed Are you sure that your performance data is correct? I noticed that your loop (set up as for (var i=0; i<len; ++i)), uses ++i, which would cause the first item in the array to be skipped.

@Mark Reed 2014-09-05 13:03:01

@CodeBling: No, it doesn't. The increment (third clause) doesn't get evaluated until after the body of the loop, so there's no difference between ++i and i++ unless there are additional expressions within that clause.

@DrBailey 2015-08-31 20:04:37

It seems like this is rather verbose for something that is extremely common. Is there a reason why there is not a simple implementation of this in standard JS?

@Mark Reed 2015-08-31 20:49:16

Well, Harmony is the new "standard"; it just hasn't been widely adopted yet. As for "why", you could ask Brendan Eich. But JS was designed and implemented in an incredibly small amount of time, by a first-time language designer. It's amazing that we got a language as good as we did. The fact that for...in iterates over indexes seems weird - until you remember that Javascript's "arrays" are really just dictionaries/objects with numeric keys. Iterating over keys makes sense because you can then use keys to extract the values, but you can't go the other way.

@João Pimentel Ferreira 2019-03-17 22:40:08

in the fourth example, using the for loop, why do you need to confirm if (i in myStringArray) ?

@sebarmeli 2010-12-07 07:24:49

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:

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.

@Jan Sverre 2012-01-02 19:47:51

myArray.forEach(function(obj) {}); is still the best

@roberkules 2012-04-12 14:58:51

a tiny improvement: you could use ++i instead of i++

@ngryman 2012-04-15 00:45:07

++i is an old school optimization that modern compilers do for you in a for loop since a long time ago :) stackoverflow.com/a/1547433/1033348

@Jose 2012-05-08 13:03:09

@Jannis .forEach has several things against it. 1) not native 2) Requires a new execution context for EVERY index which is rather expensive and seems like overkill (see dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts)

@Rui Marques 2012-11-30 13:12:20

You have to be careful using this loop. I started using it and had a hard to track bug because of one mistake I made. If you nest two loops like this: jsfiddle.net/KQwmL/1. You have to be careful to name the var len differently in the two loops, otherwise the second loop will overwrite the first len.

@Chip Hogg 2019-01-12 20:31:49

Rui Marques -- you can name your variable i_stop or i_end instead of len. It's just as readable (if not more so!), and you will naturally avoid this kind of problem (since your other loop will get, e.g., j_stop).

@MrHIDEn 2020-06-19 20:43:23

@JanSverre .forEach is the best for very short arrays. It is much better to use .map instead of. .forEach is dramatically slow, extremely slow. jsperf.com/for-of-vs-for-loop/37

@kirilloid 2012-04-15 12:50:18

There's a method to iterate over only own object properties, not including prototype's ones:

for (var i in array) if (array.hasOwnProperty(i)) {
    // Do something with array[i]

but it still will iterate over custom-defined properties.

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.

@Daniel Sokolowski 2014-10-09 14:40:54

And how about using for (var i in array) if (++i) ?

@Stijn de Witt 2013-02-28 13:59:28

I did not yet see this variation, which I personally like the best:

Given an array:

var someArray = ["some", "example", "array"];

You can loop over it without ever accessing the length property:

for (var i=0, item; item=someArray[i]; i++) {
  // item is "some", then "example", then "array"
  // i is the index of item in the array
  alert("someArray[" + i + "]: " + item);

See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/

This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in JavaScript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.

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 :)

What I like about this loop is:

  • It's short to write
  • No need to access (let alone cache) the length property
  • The item to access is automatically defined within the loop body under the name you pick.
  • 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:

for (String item : someArray) {

... with the added benefit of also knowing about the current index inside the loop

@Christian C. Salvadó 2013-02-28 18:31:03

Notice that with this approach the loop will stop as soon it finds a falsey value, such as an empty string, 0, false, NaN, null or undefined, even before i reaches the length, e.g.: jsfiddle.net/prvzk/1

@daniel1426 2014-03-20 14:17:05

The loop condition could be (item=someArray[i]) !== undefined.

@Espen 2016-10-26 08:51:39

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 safest way to iterate over an array in JavaScript.


So as others has suggested, this is almost always what you want:

var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
  sum += n;

This ensures that anything you need in the scope of processing the array stays within that 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.


var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];

for(var i = 0; i<numbers.length; ++i){
  sum += numbers[i];


will output "11" - which may or may not be what you want.

A working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/

@Alireza 2017-05-27 02:57:41

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, and you'd like to do a loop over it:

var arr = [1, 2, 3, 4, 5];

These are the solutions:

1) For loop

A for loop is a common way looping through arrays in JavaScript, but no considered as the fastest solutions for large arrays:

for (var i=0, l=arr.length; i<l; 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) {

3) Do while
A do while is doing the same thing as while with some syntax difference as below:

let i=0;
do {
while (arr.length>i);

These are the main ways to do JavaScript loops, but there are a few more ways to do that.

Also we use a for in loop for looping over objects in JavaScript.

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.

Functional programming has been making quite a splash in the development world these days. And for good reason: Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test.

One of the cornerstones of functional programming is its special use of lists and list operations. And those things are exactly what the sound like they are: arrays of things, and the stuff you do to them. But the functional mindset treats them a bit differently than you might expect.

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.

It also means you'll never have to write a for loop again.

Read more>> here:

@shea 2017-06-29 08:33:56

Is there really a performance difference before a for loop and a while loop when iterating through an array? I was under the impression the differences were primarily syntactical

@Andrew 2017-09-02 20:35:32

It seems that all the variants were listed, except forEach by lodash:

_.forEach([1, 2], (value) => {

@BILAL AHMAD 2017-09-13 22:11:03

Just a simple one-line solution:

arr = ["table", "chair"];

// Solution
arr.map((e) => {
  return e;

@Michel Jung 2017-10-06 11:09:28

You'd rather want to use .forEach() and drop the return e;

@marpme 2017-11-17 22:28:46

as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.

@colxi 2018-08-20 23:36:01

If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:


Performance results


The traditional for() iterator, is by far the fastest method, especially when used with the array length cached.

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something

The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead.

@DarckBlezzer 2018-12-10 18:19:16

is better use i = i +1 instead of i++

@PowerStat 2019-05-17 10:05:50

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)!

@colxi 2019-05-17 13:23:51

@PowerStat can you provide a link or reference about that ? I've never aheard about it, sounds interesting...

@PowerStat 2019-05-17 17:44:37

@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.

@Shijo Rs 2018-10-09 13:17:03

var array = ['hai', 'hello', 'how', 'are', 'you']
$(document).ready(function () {
  $('#clickButton').click(function () {
    for (var i = 0; i < array.length; i++) {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<input id="clickButton" value="click Me" type="button"/>
<div id="show"></div>

@domdambrogia 2019-03-05 22:46:42

Was it really necessary to bring jQuery or HTML into this?

@Yuci 2018-02-23 11:29:38

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        x: element.x * 2

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

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'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

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 }

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;


enter image description here

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');

enter image description here

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.


@jj_ 2016-03-30 02:37:14

If you want to use jQuery, it has a nice example in its documentation:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );

@hasen 2010-06-10 00:09:16

You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.

[1,2,3,4].map( function(item) {

The general syntax is:


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:

var x = [1,2,3,4].map( function(item) {return item * 10;});

And now x is [10,20,30,40].

You don't have to write the function inline. It could be a separate function.

var item_processor = function(item) {
      // Do something complicated to an item

new_list = my_list.map(item_processor);

which would be sort-of equivalent to:

 for (item in my_list) {item_processor(item);}

Except you don't get the new_list.

@hasen 2010-06-10 00:14:46

No, but it can be more powerful. check this out: joelonsoftware.com/items/2006/08/01.html

@harto 2010-06-10 00:20:47

That particular example is probably better implemented using Array.forEach. map is for generating a new array.

@Christian C. Salvadó 2010-06-10 00:30:08

@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 :)

@intuited 2010-06-10 03:06:14

It's available in some libraries, eg jQuery... but is not really meant for iterating over things. At least semantically, it doesn't imply that things actually happen in any given order. Thus the name: you are mapping one set of values to another, not processing them iteratively.

@harto 2010-06-10 04:42:30

If you check out the link CMS provided, there's an implementation you can use in browsers that don't natively support it.

@hasen 2010-06-10 08:43:39

@intuited, I'd say the same applies to the foreach loop in java/c#/python; theoretically they can be applied in a random order (i.e. in parallel across multiple processors or even multiple machines). I'd also say that the body of the foreach loop is nothing but the body of the function that's being passed to map.

@intuited 2010-06-10 16:04:12

@hasen j: that's not been my understanding, mostly based on the fact that the foreach loop is derived from the for loop rather than from functional programming concepts. Also the fact that it's called a "loop" :)

@ebruchez 2014-05-20 23:04:42

@Mark Reed 2014-09-10 17:00:23

The difference between forEach and map is that the former doesn't return the results of the iteration. map (sometimes a.k.a. collect, but very different from apply) is expressly for transforming each element of an array into a corresponding result; it's a 1-to-1 mapping, hence the name. It's part of a whole family of operations that include reduce (which produces a single result from the whole array) and filter (which produces a subset of the original array) and so on. Whereas forEach just does something with each element, semantics unspecified.

@Mark Reed 2016-03-23 15:32:18

The callback function passed to map actually gets called with three arguments: the first is the current item in the array, the second is the index of that item, and the third is a reference to the array itself. You only need to declare as many as you want as parameters, because Javascript, but they're all available.

@gengkev 2016-04-26 23:47:36

Downvote because if you're not actually mapping something, then using [].map is misleading. [].forEach makes semantic sense and also passes the same three arguments to the function.

@Muhammad Alvin 2012-04-18 14:46:06

It's not 100% identical, but similar:

   var myStringArray = ['Hello', 'World']; // array uses [] not {}
    for (var i in myStringArray) {
        console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item

@Kzqai 2012-04-18 15:34:45

It seems that this would run up against similar problems as other for in usages with an array object, in that prototype member variables would be caught by the for in as well.

@bzim 2016-08-01 21:18:18

Array loop:

for(var i = 0; i < things.length; i++){
    var thing = things[i];

Object loop:

for(var prop in obj){
    var propValue = obj[prop];

@Alongkorn Chetasumon 2016-10-14 10:31:58

In JavaScript, there are so many solutions to loop an array.

The code below are popular ones

/** Declare inputs */
const items = ['Hello', 'World']

/** Solution 1. Simple for */
console.log('solution 1. simple for')

for (let i = 0; i < items.length; i++) {


/** Solution 2. Simple while */
console.log('solution 2. simple while')

let i = 0
while (i < items.length) {


/** Solution 3. forEach*/
console.log('solution 3. forEach')

items.forEach(item => {


/** Solution 4. for-of*/
console.log('solution 4. for-of')

for (const item of items) {


@molokoloco 2014-03-08 02:06:39

The most elegant and fast way

var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
    value + 1


Edited (because I was wrong)

Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.


<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>
    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?)
        // Declare the test Array
        var arr = [];
        for (var i = 0; i < 100000; i++)
            arr[i] = i;


<a href="http://jsperf.com/native-loop-performance/16" 
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>

@Deniz Ozger 2014-03-26 15:36:11

This loop doesn't seem to follow order of items in the array.

@molokoloco 2014-03-27 16:41:40

My test was wrong. It's correct, showing all LOOPS now. jsperf.com/native-loop-performance/16

@Stijn de Witt 2014-05-15 17:34:36

@bergi is right. This loop wipes out the array as it loops through it. Not what you want in most cases.

@njzk2 2014-07-29 14:59:25

breaks on falsey items.

@kennebec 2010-06-10 02:43:29

Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.

You may not need all of them, but they can be very useful, or would be if every browser supported them.

Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.

filter returns an array of items that satisfy some condition or test.

every returns true if every array member passes the test.

some returns true if any pass the test.

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.

Ignore it until you need it.

indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.

    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;
            return A;
        every: function(fun, scope){
            var L= this.length, i= 0;
            if(typeof fun== 'function'){
                    if(i in this && !fun.call(scope, this[i], i, this))
                        return false;
                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);
            return this;
        indexOf: function(what, i){
            i= i || 0;
            var L= this.length;
            while(i< L){
                if(this[i]=== what)
                    return i;
            return -1;
        lastIndexOf: function(what, i){
            var L= this.length;
            i= i || L-1;
            if(isNaN(i) || i>= L)
                i= L-1;
                if(i< 0) i += L;
            while(i> -1){
                if(this[i]=== what)
                    return 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);
                return A;
        some: function(fun, scope){
            var i= 0, L= this.length;
            if(typeof fun== 'function'){
                    if(i in this && fun.call(scope, this[i], i, this))
                        return true;
                return false;
    for(p in p2){
            ap[p]= p2[p];
    return true;

@rwitzel 2015-04-17 15:12:25

Addition: IE supports forEach since version 9, see forEach Method MSDN

@Daniel K. 2015-12-12 03:11:44

Sure it's inefficient and many despise it, but it's one of the closest to the mentioned:

var myStringArray = ["Hello","World"];
    // Do something

@user513951 2015-12-12 03:27:28

This exact functionality is already part of Mark Reed's answer.

@Juanjo Salvador 2016-03-17 10:13:33

Short answer: yes. You can do with this:

var myArray = ["element1", "element2", "element3", "element4"];

for (i = 0; i < myArray.length; i++) {

In a browser console, you can see something like "element1", "element2", etc., printed.

@user6139250 2016-03-31 11:28:21

It is better to use a sequential for loop:

for (var i = 0; i < myStringArray.length; i++) {
    // Do something

@Sapphire_Brick 2019-09-27 18:55:06

Why is it better? of course, you can do that in java as well, bu he asked about a foreach loop.

@Shubham Khatri 2016-04-21 16:03:42

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 the .each() function.

var myStringArray = ["hello", "World"];
for(var i in myStringArray) {

var myStringArray = ["hello", "World"];
for (var i=0; i < myStringArray.length; i++) {

var myStringArray = ["hello", "World"];
$.each(myStringArray, function(index, value){
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

@brk 2016-12-05 05:25:56

for...in should be avoided for Array-like objects

@Dan Chill 2016-05-26 19:11:06

var obj = ["one","two","three"];

for(x in obj){

Related Questions

Sponsored Content

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 7136824 View
  • 8650 Score
  • 97 Answer
  • Tags:   javascript arrays

47 Answered Questions

[SOLVED] Sort array of objects by string property value

41 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

49 Answered Questions

[SOLVED] How to check if an object is an array?

30 Answered Questions

[SOLVED] How to append something to an array?

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

24 Answered Questions

[SOLVED] How to loop through a plain JavaScript object with the objects as members?

  • 2009-05-28 16:18:14
  • edt
  • 1723307 View
  • 1625 Score
  • 24 Answer
  • Tags:   javascript

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

19 Answered Questions

[SOLVED] Loop through an array of strings in Bash?

  • 2012-01-16 13:21:16
  • Mo.
  • 1286086 View
  • 1566 Score
  • 19 Answer
  • Tags:   arrays bash shell

Sponsored Content