Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

How can I loop through all the objects in an array using JavaScript?

I thought of something like this (where objects is my array of objects):

forEach(instance in objects)

But this does not seem to be correct.

share|improve this question
9  
I did look for it, but i looked for forEach and not just for. as stated, in c# it was a bit different, and that confused me :) – Dante1986 Feb 17 '12 at 13:57
13  
Array.ForEach is about 95% slower than for() in for each for Arrays in JavaScript. See this performance test online: jsperf.com/fast-array-foreach via coderwall.com/p/kvzbpa – molokoloco Mar 6 '14 at 21:00
25  
For many situations that 95% slower is not going to be significant blog.niftysnippets.org/2012/02/foreach-and-runtime-cost.html – David Sykes Mar 28 '14 at 9:11
1  
You could use jQuery library, see api.jquery.com/jquery.each It's alway better to use jQuery because of browser-compatible reasons. – vinsa May 19 at 12:42

24 Answers 24

up vote 3740 down vote accepted

For Actual Arrays

(See "For Array-Like Objects" below for array-like objects.)

You currently have three options and will soon have two more:

You have three options in ECMAScript 5 (ES5), the current version of JavaScript; and will soon have two more in ECMAScript 6 (ES6), the next version of JavaScript:

  1. Use forEach and related (ES5+)
  2. Use a simple for loop
  3. Use for-in correctly
  4. Use for-of (use an iterator implicitly) (ES6+)
  5. Use an iterator explicitly (ES6+)

Details:

1. Use forEach and related

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach function:

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

Using forEach on a general-purpose web page still (as of March 2014) requires that you include a "shim" for it for browsers that don't support it natively, because IE8 and earlier don't have it (and they're used by somewhere between 7% and 21% of the global browser users depending on who you believe; that figure is skewed a bit by markedly higher use in China vs. elsewhere, always check your own stats to see what you need to support). But shimming/polyfilling it is easily done (search for "es5 shim" for several options).

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

Additionally, forEach is the "loop through them all" function, but ES5 defined several other useful "work your way through the array and do things" functions, including:

  • every (stops looping the first time the iterator returns false or something falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • map (creates a new array from the values returned by the iterator function)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
  • reduceRight (like reduce, but works in descending rather than ascending order)

2. Use a simple for loop

Sometimes the old ways are the best:

var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}

And/or counting backward:

var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

3. Use for-in correctly

You'll get people telling you to use for-in, but that's not what for-in is for. for-in loops through the enumerable properties of an object, not the indexes of an array. Up through ES5, the order is not guaranteed; as of ES6, the order is guaranteed (by [[OwnPropertyKeys]], [[Enumerate]], and the definition of for-in/for-of). (Details in this other answer.)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

  1. That the object has its own property by that name (not one it inherits from its prototype), and

  2. That the key is a base-10 numeric string in its normal string form and its value is <= 2^32 - 2 (which is 4,294,967,294). Where does that number come from? It's part of the definition of an array index in the specification, §10.5. Other numbers (non-integers, negative numbers, numbers greater than 2^32 - 2) are not array indexes. The reason it's 2^32 - 2 is that that makes the greatest index value one lower than 2^32 - 1, which is the maximum value an array's length can have. (E.g., an array's length fits in a 32-bit unsigned integer.) (Props to RobG for pointing out in a comment on my blog post that my previous test wasn't quite right.)

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0", "10", and "10000" — remember, they're strings), not 10,001 times.

Now, you won't want to write that every time, so you might put this in your toolkit:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}

And then we'd use it like this:

for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

4. Use for-of (use an iterator implicitly) (ES6+)

ES6 (currently being finalized) will add iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Output:

a
b
c

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

5. Use an iterator explicitly (ES6+)

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.

(As of this writing, Firefox 29 supports entries and keys but not values.)

For Array-Like Objects

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

Use any of the options above for arrays

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

  1. Use forEach and related (ES5+)

    The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

    Suppose you wanted to use forEach on a Node's childNodes property. You'd do this:

    Array.prototype.forEach.call(node.childNodes, function(child) {
        // Do something with `child`
    });
    

    If you're going to do that a lot, you might want to grab a copy of the function reference into a variable for reuse, e.g.:

    // (This is all presumably in some scoping function)
    var forEach = Array.prototype.forEach;
    
    // Then later...
    forEach.call(node.childNodes, function(child) {
        // Do something with `child`
    });
    
  2. Use a simple for loop

    Obviously, a simple for loop applies to array-like objects.

  3. Use for-in correctly

    for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

  4. Use for-of (use an iterator implicitly) (ES6+)

    for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

  5. Use an iterator explicitly (ES6+)

    See #4, we'll have to see how iterators play out.

Create a true array

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

  1. Use the slice method of arrays

    We can use the slice method of arrays, which like the other methods mentioned above is "intentionally generic" and so can be used with array-like objects, like this:

    var trueArray = Array.prototype.slice.call(arrayLikeObject);
    

    So for instance, if we want to convert a NodeList into a true array, we could do this:

    var divs = Array.prototype.slice.call(document.querySelectorAll("div"));
    

    See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

  2. Use the spread operator (...)

    It's also possible to use the ES6 spread operator, with JavaScript engines that support this feature:

    var trueArray = [...iterableObject];
    

    So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

    var divs = [...document.querySelectorAll("div")];
    

Caveat for host-provided objects

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the spec does allow for the possibility a host-provided object may not be honest; it's in §8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

share|improve this answer
11  
I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break. – Pius May 6 '13 at 20:12
19  
@Pius: If you want to break the loop, you can use some. (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) ) – T.J. Crowder May 6 '13 at 21:17
7  
if you're using ie8 you can paste in this code to use forEach. if ( !Array.prototype.forEach ) { Array.prototype.forEach = function(fn, scope) { for(var i = 0, len = this.length; i < len; ++i) { fn.call(scope, this[i], i, this); } }; } developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – CharlesTWall3 Jun 19 '13 at 18:43
4  
Why ++index and not index++? The first key should be 0. – FMC Feb 3 '14 at 2:41
7  
@FMC: Where I'm using it above, it doesn't make any difference whether it's ++index or index++; we're not using the result of that expression. The first value index will have in the loop is 0 either way. I used ++index because I speak English, and so "increment index" makes more sense to me than "index increment". But whichever you prefer is fine there. – T.J. Crowder Feb 3 '14 at 10:43

Edit: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:

  • forEach
  • map
  • filter
  • zip
  • reduce
  • every
  • some

The standard way to iterate an array in JavaScript is a vanilla for-loop:

var length = arr.length,
    element = null;
for (var i = 0; i < length; i++) {
  element = arr[i];
  // Do something with element i.
}

Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a for .. in-loop might be a better idea. However, you must use the appropriate safeguards to ensure that only the desired properties of the array (that is, the array elements) are acted upon, since the for..in-loop will also be enumerated in legacy browsers, or if the additional properties are defined as enumerable.

In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include.

share|improve this answer
    
why is for(instance in objArray) not a correct usage ? it looks more simple to me, but i hear you speak of it as not a correct way for usage ? – Dante1986 Feb 17 '12 at 14:12
12  
You can use inline length caching: for (var i = 0, l = arr.length; i < l; i++) – Robert Jul 13 '13 at 1:35
    
Is the comma at the end of first line intentional, or is it a typo(could be semicolon)? – Mohd Abdul Mujib Nov 18 '13 at 6:52
3  
@wardha-Web It is intentional. It enables us to declare multiple variables with a single var-keyword. If we had used a semicolon, then element would have been declared in the global scope (or, rather, JSHint would have screamed at us before it reached production). – PatrikAkerstrand Nov 18 '13 at 12:22

If you’re using the jQuery library, you can use jQuery.each:

$.each(yourArray, function(index, value) {
  // do your stuff here
});

EDIT : As per question, user want code in javascript instead of jquery so the edit is

var length = yourArray.length;   
for (var i = 0; i < length; i++) {
  // Do something with yourArray[i].
}
share|improve this answer
    
I am probably going to use this answer the most often. It is not the best answer to the question, but in practice is going to be the simplest and most applicable for those of us using jQuery. I do think we should all learn the vanilla way also though. It never hurts to expand your understanding. – mopsyd Sep 4 '13 at 16:01
20  
Just for the sake of it: jQuery each is much slower then native solutions. It is advised by jQuery to use native JavaScript instead of jQuery when ever it is possible. jsperf.com/browser-diet-jquery-each-vs-for-loop – Kevin Boss Oct 7 '13 at 13:04
2  
Refrain from using jQuery when you can use vanilla js – Noe Oct 9 '13 at 19:38
    
Stick to standard JS, keep the 3rd party libraries out of the answer unless there isn't a native language solution – Steve K Dec 10 '14 at 6:48
    
Kind of reminds me of this: i.stack.imgur.com/ssRUr.gif – Ajedi32 Jan 2 at 19:40

Some C-style languages use foreach to loop through enumerations. In JavaScript this is done with the for..in loop structure:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

There is a catch. for..in will loop through each of the object's enumerable members, and the members on its prototype. To avoid reading values that are inherited through the object's prototype, simply check if the property belongs to the object:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

Additionally, ECMAScript 5 has added a forEach method to Array.prototype which can be used to enumerate over an array using a calback (the polyfill is in the docs so you can still use it for older browsers):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

It's important to note that Array.prototype.forEach doesn't break when the callback returns false. jQuery and Underscore.js provide their own variations on each to provide loops that can be short-circuited.

share|improve this answer
1  
So how does one break out of a a ECMAScript5 foreach loop like we would for a normal for loop or a foreach loop like that found in C-style languages? – Ciaran Gallagher Mar 3 '13 at 18:35
3  
@CiaranG, in JavaScript it's common to see each methods that allow return false to be used to break out of the loop, but with forEach this isn't an option. An external flag could be used (ie if (flag) return;, but it would only prevent the rest of the function body from executing, forEach would still continue iterating over the entire collection. – zzzzBov Mar 3 '13 at 19:08

Loop backwards

I think the reverse for loop deserves a mention here:

for (var i=array.length; i--; ) {
     // process array[i]
}

Advantages:

  • You do not need to declare a temporary len variable, or compare against array.length on each iteration, either of which might be a minute optimisation.
  • Removing siblings from the DOM in reverse order is usually more efficient. (The browser needs to do less shifting of elements in its internal arrays.)
  • If you modify the array while looping, at or after index i (for example you remove or insert an item at array[i]), then a forward loop would skip the item that shifted left into position i, or re-process the ith item that was shifted right. In a traditional for loop, you could update i to point to the next item that needs processing - 1, but simply reversing the direction of iteration is often a simpler and more elegant solution.
  • Similarly, when modifying or removing nested DOM elements, processing in reverse can circumvent errors. For example, consider modifying the innerHTML of a parent node before handling its children. By the time the child node is reached it will be detached from the DOM, having been replaced by a newly created child when the parent's innerHTML was written.
  • It is shorter to type, and read, than some of the other options available. Although it loses to forEach() and to ES6's for ... of.

Disadvantages:

  • It processes the items in reverse order. If you were building a new array from the results, or printing things on screen, naturally the output will be reversed with respect to the original order.
  • Repeatedly inserting siblings into the DOM as a first child in order to retain their order is less efficient. (The browser would keep having to shift things right.) To create DOM nodes efficiently and in order, just loop forwards and append as normal (and also use a "document fragment").
  • The reverse loop is confusing to junior developers. (You may consider that an advantage, depending on your outlook.)

Should I always use it?

Some developers use the reverse for loop by default, unless there is a good reason to loop forwards.

Although the performance gains are usually insignificant, it sort of screams:

"Just do this to every item in the list, I don't care about the order!"

However in practice that is not actually a reliable indication of intent, since it is indistinguishable from those occasions when you do care about the order, and really do need to loop in reverse. So in fact another construct would be needed to accurately express the "don't care" intent, something currently unavailable in most languages, including ECMAScript, but which could be called, for example, forEachUnordered().

If order doesn't matter, and efficiency is a concern (in the innermost loop of a game or animation engine), then it may be acceptable to use the reverse for loop as your go-to pattern. Just remember that seeing a reverse for loop in existing code does not necessarily mean that the order irrelevant!

It is better to use forEach()

In general for higher level code where clarity and safety are greater concerns, I would recommend using Array::forEach as your default pattern:

  • It is clear to read.
  • It indicates that i is not going to be shifted within the block (which is always a possible surprise hiding in long for and while loops.)
  • It gives you a free scope for closures.
  • It reduces leakage of local variables and accidental collision with (and mutation of) outer variables.
  • But note that unlike map, forEach does not exclude the possibility that the loop will break out part-way through. This is a feature that can be triggered by returning false from the callback.

Then when you do see the reverse for loop in your code, that is a hint that it is reversed for a good reason (perhaps one of the reasons described above). And seeing a traditional forward for loop may indicate that shifting can take place.

(If the discussion of intent makes no sense to you, then you and your code may benefit from watching Crockford's lecture on Programming Style & Your Brain.)


How does it work?

for (var i=0; i<array.length; i++) { ... }   // Forwards

for (var i=array.length; i--; )    { ... }   // Reverse

You will notice that i-- is the middle clause (where we usually see a comparison) and the last clause is empty (where we usually see i++). That means that i-- is also used as the condition for continuation. Crucially, it is executed and checked before each iteration.

  • How can it start at array.length without exploding?

    Because i-- runs before each iteration, on the first iteration we will actually be accessing the item at array.length-1 which avoids any issues with Array-out-of-bounds undefined items.

  • Why doesn't it stop iterating before index 0?

    The loop will stop iterating when the condition i-- evaluates to a falsey value (when it yields 0).

    The trick is that unlike --i, the trailing i-- operator decrements i but yields the value before the decrement. Your console can demonstrate this:

    > var i = 5; [i, i--, i];

    [5, 5, 4]

    So on the final iteration, i was previously 1 and the i-- expression changes it to 0 but actually yields 1 (truthy), and so the condition passes. On the next iteration i-- changes i to -1 but yields 0 (falsey), causing execution to immediately drop out of the bottom of the loop.

    In the traditional forwards for loop, i++ and ++i are interchangeable (as Douglas Crockford points out). However in the reverse for loop, because our decrement is also our condition expression, we must stick with i-- if we want to process the item at index 0.


Trivia

Some people like to draw a little arrow in the reverse for loop, and end with a wink:

for (var i=array.length; i-->0 ;) {

Credits go to WYL for showing me the benefits and horrors of the reverse for loop.

share|improve this answer
1  
I forgot to add the benchmarks. I also forgot to mention how reverse looping is a significant optimization on 8-bit processors like the 6502, where you really do get the comparison for free! – joeytwiddle May 2 '14 at 15:14
    
That trivia for loop is too clever for its own good. Would make for an interesting interview question. – Clay Jan 7 at 21:17
    
How about this for a reverse loop? var i= array.length; while(i--) { ... – Kabb5 May 15 at 16:32

A forEach implementation (see in jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);
share|improve this answer
    
iterator in this, is doing a needless length calculation. In an ideal case, the list length should be calculated only once. – MIdhun Krishna Dec 18 '13 at 9:47
    
@MIdhunKrishna I updated my answer and the jsFiddle but be aware that it is not as simple as you think. Check this question – nmoliveira Dec 18 '13 at 12:36

If you don't mind emptying the array:

var x;

while(x = y.pop()){ 

    alert(x); //do something 

}

x will contain the last value of y and it will be removed from the array. You can also use shift() which will give and remove the first item from y.

share|improve this answer

If you want to loop over an array, use the standard three-part for loop.

for (var i = 0; i < myArray.length; i++) {
    var arrayItem = myArray[i];
}

You can get some performance optimisations by caching myArray.length or iterating over it backwards.

share|improve this answer
3  
for (var i = 0, length = myArray.length; i < length; i++) should do it – Edson Medina Mar 28 '13 at 2:20
1  
@EdsonMedina That will also create a new global variable called length. ;) – joeytwiddle May 30 '14 at 18:55
1  
@joeytwiddle Yes, but that's beyond the scope of this post. You'll create a global variable i anyway. – Edson Medina Jun 1 '14 at 11:03
2  
@EdsonMedina The variable i will be local to the function, but length will truly leak into the global; it will be visible as window.length! (This is because JS is a bitch: the var keyword does not reach length because i=0 is a statement.) To keep both i and len local to the function we must declare all the variables before assign values to them: for (var i, len, i = 0, len = myArray.length; i < len; i++) – joeytwiddle Jun 1 '14 at 16:05
2  
@EdsonMedina My apologies, I had that completely wrong. Using , after an assignment does not introduce a new global, so your suggestion is just fine! I was confusing this for a different problem: Using = after an assignment does create a new global. – joeytwiddle Jul 22 '14 at 10:17

There are three implementations of foreach in jQuery as follows.

var a = [3,2];

$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3
share|improve this answer
    
+1 for mentioning jquery, -1 for the irrelevant and confusing console.log stuff. – richard Feb 13 '14 at 20:58
1  
Console log is just for the demo. That's to make it a cmplete running example. – Rajesh Paul Feb 15 '14 at 4:05

An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as each and will automatically delegate the job to the native forEach if available.

A CodePen example of how it works is:

var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});

See also

share|improve this answer

Probably the for(i = 0; i < array.length; i++) loop is not the best choice. Why? If you have this:

var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";

The method will call from array[0] to array[2]. First, this will first reference variables you don't even have, second you would not have the variables in the array, and third this will make the code bolder. Look here, it's what I use:

for(var i in array){
    var el = array[i];
    //If you want 'i' to be INT just put parseInt(i)
    //Do something with el
}

And if you want it to be a function, you can do this:

function foreach(array, call){
    for(var i in array){
        call(array[i]);
    }
}

If you want to break, a little more logic:

function foreach(array, call){
    for(var i in array){
        if(call(array[i]) == false){
            break;
        }
    }
}

Example:

foreach(array, function(el){
    if(el != "!"){
        console.log(el);
    } else {
        console.log(el+"!!");
    }
});

It returns:

//Hello
//World
//!!!
share|improve this answer

I know this is an old post, and there are so many great answers already. For a little more completeness I figured I'd throw in another one using AngularJS. Of course, this only applies if you're using Angular, obviously, nonetheless I'd like to put it anyway.

angular.forEach takes 2 arguments and an optional third argument. The first argument is the object (array) to iterate over, the second argument is the iterator function, and the optional third argument is the object context (basically referred to inside the loop as 'this'.

There are different ways to use the forEach loop of angular. The simplest and probably most used is

var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
    //item will be each element in the array
    //do something
});

Another way that is useful for copying items from one array to another is

var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
    this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);

Though, you don't have to do that, you can simply do the following and it's equivalent to the previous example:

angular.forEach(temp, function(item) {
    temp2.push(item);
});

Now there are pros and cons of using the angular.forEach function as opposed to the built in vanilla-flavored for loop.

Pros

  • Easy readability
  • Easy writability
  • If available, angular.forEach will use the ES5 forEach loop. Now, I will get to efficientcy in the cons section, as the forEach loops are much slower than the for loops. I mention this as a pro because it's nice to be consistent and standardized.

Consider the following 2 nested loops, which do exactly the same thing. Let's say that we have 2 arrays of objects and each object contains an array of results, each of which has a Value property that's a string (or whatever). And let's say we need to iterate over each of the results and if they're equal then perform some action:

angular.forEach(obj1.results, function(result1) {
    angular.forEach(obj2.results, function(result2) {
        if (result1.Value === result2.Value) {
            //do something
        }
    });
});

//exact same with a for loop
for (var i = 0; i < obj1.results.length; i++) {
    for (var j = 0; j < obj2.results.length; j++) {
        if (obj1.results[i].Value === obj2.results[j].Value) {
            //do something
        }
    }
}

Granted this is a very simple hypothetical example, but I've written triple embedded for loops using the second approach and it was very hard to read, and write for that matter.

Cons

  • Efficiency. angular.forEach, and the native forEach, for that matter, are both so much slower than the normal for loop....about 90% slower. So for large data sets, best to stick to the native for loop.
  • No break, continue, or return support. continue is actually supported by "accident", to continue in an angular.forEach you simple put a return; statement in the function like angular.forEach(array, function(item) { if (someConditionIsTrue) return; }); which will cause it to continue out of the function for that iteration. This is also due to the fact that the native forEach does not support break or continue either.

I'm sure there's various other pros and cons as well, and please feel free to add any that you see fit. I feel that, bottom line, if you need efficiency, stick with just the native for loop for your looping needs. But, if your datasets are smaller and a some efficiency is okay to give up in exchange for readability and writability, then by all means throw an angular.forEach in that bad boy.

share|improve this answer
var i, len;
for( i=0, len=array.length ; i<len ; i++){
    // here, array[i] is the current element
}
share|improve this answer

There isn't any for each loop in native JavaScript. You can either use libraries to get this functionality (I recommend Underscore.js), use a simple for in loop.

for (var instance in objects) {
   ...
}

However, note that there may be reasons to use an even simpler for loop (see Stack Overflow question Why is using “for…in” with array iteration such a bad idea?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];
    ...
}
share|improve this answer

This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)

function each( fn, data ) {

    if(typeof fn == 'string')
        eval('fn = function(data, i){' + fn + '}');

    for(var i=0, L=this.length; i < L; i++) 
        fn.call( this[i], data, i );   

    return this;
}

Array.prototype.each = each;  

Examples of usage:

Example #1

var arr=[];
[1,2,3].each( function(a){ a.push( this * this},arr);

arr is now = [1, 4, 9]

Example #2

each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');

Each p tag gets class="blue"

Example #3

each.call(document.getElementsByTagName('p'), 
    "if( i % 2 == 0) this.className = data;",
    'red'
);

Every other p tag gets class="red">

Example #4

each.call(document.querySelectorAll('p.blue'), 
    function(newClass, i) {
        if( i < 20 )
            this.className = newClass;
    },'green'
);

And finally, the first 20 blue p tags are changed to green

Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive.

share|improve this answer

Internet Explorer 8 and below don't support forEach. Here's a polyfill for non supporting browsers;

if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      if (i in this) {
        fn.call(scope, this[i], i, this);
      }
    }
  };
}

It is taken from Mozilla's documentation.

share|improve this answer
    
THIS DOUS NOT WORK! in ie9 on vista, ie8 at all.. so dont use it.. – Sangoku Jun 3 '14 at 8:27
    
IE9 has forEach natively. I don't see why it shouldn't work. And the polyfill definitely works for IE8 or even 7. Are you using it in the correct way? – Pratheep Jun 7 '14 at 12:07
    
you should not alter objects that don't belong to you – user2359695 Oct 3 '14 at 20:02

I think that the best and standard way is to use the for loop, and I like the short way to write it:

var list = ["a", "b", "c"];
for (var i = 0, letter; letter=list[i]; i++) {
     alert(letter) ;
}
share|improve this answer
    
Two useful variables out of 1 line, and it doesn't break if array length changes. – James Jan 19 at 22:13

ECMAScript 6 will maybe contain the "for...of" construct. See for...of (MDN) for more information. You can already try it out with recent Firefox versions.

share|improve this answer

jQuery way using $.map:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];
share|improve this answer

Use:

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

where [ 52, 97 ] is your array.

This produces two messages:

0: 52
1: 97

$.each() is essentially a drop-in replacement of a traditional for or for-in loop.

Example

// **Traditional JavaScript code**

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

for ( var i = 0, l = arr.length; i < l; i++ ) {
    sum += arr[ i ];
}
console.log( sum ); // 15

It can be replaced with this using jQuery:

$.each( arr, function( index, value ){
    sum += value;
});
console.log( sum ); // 15

Using JavaScript

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    alert(myStringArray[i]);
    //Do something
}
share|improve this answer

There's no built-in ability to break in forEach. To interrupt execution use of Array#some:

[1,2,3].some(function(number) {
    return number === 1;
});

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest. Original Answer see Arrary prototype for some

share|improve this answer

One more thing about array.forEach. You can get not only index, but also the iterated object with forEach, if you have array of objects:

var fruits = [{'name': 'banana'}, {'name': 'apple'}, {'name': 'pear'}, {'name': 'watermelon'}];

fruits.forEach(function(fruit, i) {
  console.log('name of fruit no. ' + i + ' is: ' + fruit.name);
});
share|improve this answer

This code list array value using forEach loop.

<script>
(function(){
var names = new Array();
    names[0]='sunny';
    names[1]= 'Raj';
    names[2]='Reena'

    var showList = function(element, index, array){
        console.log('Name[' + index + '] = ' + element);
    }

    names.forEach(showList );
})();
</script>
share|improve this answer

I also would like to add this as a composition of reverse loop and an answer above for someone that would like this syntax too.

var foo = [object,object,object];
for(var i = foo.length , item ; item = foo[--i] ;){
   console.log(item);
}

Pros : The benefit for this , you have the reference already in the first like that wont need to declared later with another line. Handy when looping trough the object array.

Cons: This will break whenever reference is false - falsey (undefined etc). Can be used as an advantage though , however it would make it to read a little bit harder

share|improve this answer

protected by hjpotter92 Apr 3 '14 at 15:03

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.