By Dante1986


2012-02-17 13:51:48 8 Comments

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

I thought it was something like this:

forEach(instance in theArray)

Where theArray is my array, but this seems to be incorrect.

30 comments

@subhashish negi 2019-03-08 14:04:09

if you want to loop through array of objects with arrow function:

let arr=[{name:'john',age:50},{name:'clark',age:19},{name:'mohan',age:26}];

arr.forEach((person)=>{
  console.log('i am '+person.name+' and i am '+person.age+ ' old');
})

@Ayush Jain 2019-03-11 08:56:15

You can use forEach() API (provided by Javascript) which accepts a function as a callback and runs one time for each element present inside the array.

https://fullstackgeek.blogspot.com/2019/01/arrays-in-javascript-part-2.html

@T.J. Crowder 2012-02-17 13:53:44

TL;DR

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • Your best bets are usually

    • a for-of loop (ES2015+ only),
    • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
    • a simple old-fashioned for loop,
    • or for-in with safeguards.

But there's lots more to explore, read on...


JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the arguments object, other iterable objects (ES2015+), DOM collections, and so on.

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

Okay, let's look at our options:

For Actual Arrays

You have three options in ECMAScript 5 ("ES5"), the version most broadly supported at the moment, and two more added in ECMAScript 2015 ("ES2015", "ES6"):

  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) (ES2015+)
  5. Use an iterator explicitly (ES2015+)

Details:

1. Use forEach and related

In any vaguely-modern environment (so, not IE8) where you have access to the Array features added by ES5 (directly or using polyfills), you can use forEach (spec | MDN):

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

forEach accepts a callback function and, optionally, a value to use as this when calling that callback (not used above). The callback 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 callback 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).

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September 2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach 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 callback returns false or something falsey)
  • some (stops looping the first time the callback 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 callback)
  • reduce (builds up a value by repeatedly calling the callback, 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.

In ES2015 and higher, you can make your index and value variables local to the for loop:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
    console.log(index, value);
}
//console.log(index);   // would cause "ReferenceError: index is not defined"
//console.log(value);   // would cause "ReferenceError: value is not defined"

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
    console.log(index, value);
}
try {
    console.log(index);
} catch (e) {
    console.error(e);   // "ReferenceError: index is not defined"
}
try {
    console.log(value);
} catch (e) {
    console.error(e);   // "ReferenceError: value is not defined"
}

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        console.log("Index is: " + index);
    });
}

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        console.log("Index is: " + index);
    });
}
<div>zero</div>
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

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. The order is not guaranteed, not even in ES2015 (ES6). ES2015+ does define an order to object properties (via [[OwnPropertyKeys]], [[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

The only real use cases for for-in on an array are:

  • It's a sparse arrays with massive gaps in it, or
  • You're using non-element properties and you want to include them in the loop

Looking only at that first example: You can use for-in to visit those sparese array elements 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 checks are
        /^0$|^[1-9]\d*$/.test(key) &&    // explained
        key <= 4294967294                // below
        ) {
        console.log(a[key]);
    }
}

Note the three 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 all decimal digits (e.g., normal string form, not scientific notation), and

  3. That the key's value when coerced to a number 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. 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.)

You wouldn't do that in inline code, of course. You'd write a utility function. Perhaps:

// Utility function for antiquated environments without `forEach`
var hasOwn = Object.prototype.hasOwnProperty;
var rexNum = /^0$|^[1-9]\d*$/;
function sparseEach(array, callback, thisArg) {
    var index;
    for (var key in array) {
        index = +key;
        if (hasOwn.call(a, key) &&
            rexNum.test(key) &&
            index <= 4294967294
            ) {
            callback.call(thisArg, array[key], index, array);
        }
    }
}

var a = [];
a[5] = "five";
a[10] = "ten";
a[100000] = "one hundred thousand";
a.b = "bee";

sparseEach(a, function(value, index) {
    console.log("Value at " + index + " is " + value);
});

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

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

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

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 (ES2015+)

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:

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

The iterator is an object matching the Iterator definition in the specification. Its next method returns a new result object each time you call it. The result object has a property, done, telling us whether it's done, and a property value with the value for that iteration. (done is optional if it would be false, value is optional if it would be undefined.)

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 array entry for that iteration ("a", "b", and "c" in the example earlier).
  • 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.

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) (ES2015+)

    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. For instance, the specification for the NodeList from querySelectorAll was updated to support iteration. The spec for the HTMLCollection from getElementsByTagName was not.

  5. Use an iterator explicitly (ES2015+)

    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 spread syntax (...)

    It's also possible to use ES2015's spread syntax 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")];
    
  3. Use Array.from (spec) | (MDN)

    Array.from (ES2015+, but easily polyfilled) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

    var divs = Array.from(document.querySelectorAll("div"));
    

    Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

    // Arrow function (ES2015):
    var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);
    
    // Standard function (since `Array.from` can be shimmed):
    var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
        return element.tagName;
    });
    

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 5.1 spec did 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.

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) 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.)

@Pijusn 2013-05-06 20:12:52

I would also like to add that .forEach cannot be broken efficiently. You have to throw an exception to perform the break.

@T.J. Crowder 2013-05-06 21:17:55

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

@Pijusn 2013-05-06 21:23:12

@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.

@Alex Yaroshevich 2014-12-15 12:11:33

Never call list.length in test expression if list wasn't changed.

@hindmost 2015-01-12 12:36:28

Regarding caveat for host-provided objects: How exactly could I test the host object behaves properly? What is the object's honest answer to the abstract [[HasProperty]] operation?

@Khaled.K 2015-08-05 06:38:37

Also, one can implement an iterator with validNext function that moves until an item that satisfy your conditions

@user889030 2017-04-07 09:32:35

its giving me error unexpected token ; :: for(k=0;len = this.data.length; k<len; ++k){

@T.J. Crowder 2017-04-07 09:41:49

@user889030: You need a , after k=0, not a ;. Remember, programming is many things, one of which is close attention to detail... :-)

@Aluan Haddad 2017-04-17 09:51:48

@Punit.. and not a character too long. This is comprehensive and starts with the right default. If you stop at forEach and say OK, that sounds good enough for me, you will be on a good path. Big +1 for listing it first.

@JimB 2017-04-24 15:37:11

If performance is a concern maybe better not to call the length method on the array each time the loop iterates. Instead of for (index = 0; index < a.length; ++index)... how about var arrayLength = a.length; for(index = 0; index < arrayLength; ++index)...

@T.J. Crowder 2017-04-24 15:40:09

@JimB: That's covered above (and length isn't a method). :-)

@Shammel Lee 2017-06-03 03:12:10

Method 2 is typically the most efficient.

@xgqfrms 2017-08-29 15:38:01

for of & Object.keys()

@Sajith Mantharath 2017-11-22 09:28:21

Which one have best performance?

@T.J. Crowder 2017-11-22 09:29:43

@SajithMantharath: That depends on many factors. And usually doesn't matter.

@Sombrero 2017-12-18 13:25:00

.map() is faster than .forEach() codeburst.io/javascript-map-vs-foreach-f38111822c0f

@T.J. Crowder 2017-12-18 13:26:44

@Sombrero: It may be if you're doing a map operation. If you aren't, it's slower, and very much the wrong tool.

@Power Engineering 2017-12-27 15:32:45

Wonderful masterpiece lesson in code for JS arrays of objects. I guess everyone dealing with JS should know this. ;-)

@Sebastian Simon 2018-01-04 11:21:22

@ShammelLee All methods have the same efficiency in terms of time complexity. They’re all O(n).

@Mukyuu 2019-03-06 10:21:09

I prefer using for-of than forEach since it affects async operation in the Angular project which I do.

@T.J. Crowder 2019-05-18 08:04:09

@TheMaster - Online, yes; SSL, no. (I'll change that at some point.) The links above are http:, not https:.

@alejoko 2019-02-02 15:13:00

If you want to keep your code in the functional way, use map:

theArray.map(instance => do_something);

At this way you will generate new array to future operation and will skip any not desirable side effect.

@arul prince 2019-01-21 13:08:19

// Looping through arrays using foreach  ES6 way

var data = new Array(1,2,3,4,5);
data.forEach((val,index) => {
    console.log("index :",index); // index
	console.log("value :", val); // value
});

@Harunur Rashid 2018-05-30 09:05:30

If you want to use forEach(), it will look like -

theArray.forEach ( element => {
    console.log(element);
});

If you want to use for(), it will look like -

for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}

@Peko Chan 2018-12-12 11:06:29

I come from python and I found this way much clearer.
theArray being the the array, instance being the element of the array

for(let instance of theArray)
{
    console.log("The instance",instance);
}

or

for( instance in theArray)
{
  console.log("The instance",instance);
}

compare to:

theArray.forEach(function(instance) {
    console.log(instance);
});

but at the end of the day both are doing the same thing

@darklightcode 2018-10-09 20:19:52

Using Loops with ES6 destructuring and spread operator

Destructuring and the using of spread operator have proven quite useful for newcomers to ES6 as being more human-readable/aesthetic, although some javascript veterans might consider it messy, juniors or some other people might find it useful.

The following examples will use for...of statement and .forEach method.

Examples 6, 7 and 8 can be used with any functional loops like .map, .filter, .reduce, .sort, .every, .some, for more information about these methods check out the Array Object.

Example 1: Normal for...of loop - no tricks here.

let arrSimple = ['a', 'b', 'c'];

for (let letter of arrSimple) {
  console.log(letter);
}

Example 2: Split words to characters

let arrFruits = ['apple', 'orange', 'banana'];

for (let [firstLetter, ...restOfTheWord] of arrFruits) {
  // Create a shallow copy using the spread operator
  let [lastLetter] = [...restOfTheWord].reverse();
  console.log(firstLetter, lastLetter, restOfTheWord);

}

Example 3: Looping with a key and value

// let arrSimple = ['a', 'b', 'c'];

// Instead of keeping an index in `i` as per example `for(let i = 0 ; i<arrSimple.length;i++)`
// this example will use a multi-dimensional array of the following format type: 
// `arrWithIndex: [number, string][]`

let arrWithIndex = [
  [0, 'a'],
  [1, 'b'],
  [2, 'c'],
];

// Same thing can be achieved using `.map` method
// let arrWithIndex = arrSimple.map((i, idx) => [idx, i]);

// Same thing can be achieved using `Object.entries`
// NOTE: `Object.entries` method doesn't work on internet explorer unless it's polyfilled
// let arrWithIndex = Object.entries(arrSimple);

for (let [key, value] of arrWithIndex) {
  console.log(key, value);
}

Example 4: Get object properties inline

let arrWithObjects = [{
    name: 'Jon',
    age: 32
  },
  {
    name: 'Elise',
    age: 33
  }
];

for (let { name, age: aliasForAge } of arrWithObjects) {
  console.log(name, aliasForAge);
}

Example 5: Get deep object properties of what you need

let arrWithObjectsWithArr = [{
    name: 'Jon',
    age: 32,
    tags: ['driver', 'chef', 'jogger']
  },
  {
    name: 'Elise',
    age: 33,
    tags: ['best chef', 'singer', 'dancer']
  }
];

for (let { name, tags: [firstItemFromTags, ...restOfTags] } of arrWithObjectsWithArr) {
  console.log(name, firstItemFromTags, restOfTags);
}

Example 6: Is Example 3 used with .forEach

let arrWithIndex = [
  [0, 'a'],
  [1, 'b'],
  [2, 'c'],
];

// Not to be confused here, `forEachIndex` is the real index
// `mappedIndex` was created by "another user", so you can't really trust it

arrWithIndex.forEach(([mappedIndex, item], forEachIndex) => {
  console.log(forEachIndex, mappedIndex, item);
});

Example 7: Is Example 4 used with .forEach

let arrWithObjects = [{
    name: 'Jon',
    age: 32
  },
  {
    name: 'Elise',
    age: 33
  }
];
// NOTE: Destructuring objects while using shorthand functions 
// are required to be surrounded by parenthesis
arrWithObjects.forEach( ({ name, age: aliasForAge }) => {
  console.log(name, aliasForAge)
});

Example 8: Is Example 5 used with .forEach

let arrWithObjectsWithArr = [{
    name: 'Jon',
    age: 32,
    tags: ['driver', 'chef', 'jogger']
  },
  {
    name: 'Elise',
    age: 33,
    tags: ['best chef', 'singer', 'dancer']
  }
];

arrWithObjectsWithArr.forEach(({
  name,
  tags: [firstItemFromTags, ...restOfTags]
}) => {
  console.log(name, firstItemFromTags, restOfTags);
});

@PatrikAkerstrand 2012-02-17 13:55:11

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
}

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.

@Dante1986 2012-02-17 14:12:07

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 ?

@Robert 2013-07-13 01:35:48

You can use inline length caching: for (var i = 0, l = arr.length; i < l; i++)

@Mohd Abdul Mujib 2013-11-18 06:52:18

Is the comma at the end of first line intentional, or is it a typo(could be semicolon)?

@PatrikAkerstrand 2013-11-18 12:22:15

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

@Willem van der Veen 2018-09-08 07:55:57

Summary:

When iterating over an array we often can want to accomplish one of the following goals:

  1. We want to iterate over the array and create new array:

    Array.prototype.map

  2. We want to iterate over the array and don't create a new array:

    Array.prototype.forEach

    for..of loop

In JS there are many ways of accomplishing both of these goals. However, some are more conventient than others. Below you can find some commonly used methods (the most conventient imo) to accomplish array iteration in javascript.

Creating new array: Map

map() is a function located on Array.prototype which can transform every element of an array and then returns an new array. map() takes as an argument a callback function and works in the following manner:

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

let newArr = arr.map((element, index, array) => {
  return element * 2;
})

console.log(arr);
console.log(newArr);

The callback which we have passed into map() as an argument gets executed for every element. Then an array gets returned which has the same length as the original array. In this new array element is transformed by the callback function passed in as an argument to map().

The distinct difference between map and other loop mechanism like forEach and a for..of loop are that map returns as new array and leaves the old array intact (except if you explicity manipulate it with thinks like splice).

Also note that the map function's callback provides as a second argument the index number of the current iteration. Furthermore does the third argument provide the array on which map was called. Sometimes these properties can be very useful.

Loop using forEach

forEach is a function which is located on Array.prototype which takes a callback function as an argument. It then executes this callback function for every element in the array. In contrast to the map() function the forEach function returns nothing (undefined). For example:

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

arr.forEach((element, index, array) => {

  console.log(element * 2);

  if (index === 4) {
    console.log(array)
  }
  // index, and oldArray are provided as 2nd and 3th argument by the callback

})

console.log(arr);

Just like the map function, the forEach callback provides as a second argument the index number of the current iteration. Also does the third argument provide the array on which forEach was called.

Loop through elements using for..of

The for..of loop loops through every element of an array (or any other iterable object). It works in the following manner:

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

for(let element of arr) {
  console.log(element * 2);
}

In the above example element stands for an array element and arr is the array which we want to loop. Not that the name element is arbitrary and we could have picked any other name like 'el' or something more declarative when this is applicable.

Don't confuse the for..in loop with the for..of loop. for..in will loop through all enumerable properties of the array whereas the for..of loop will only loop through the array elements. For example:

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

arr.foo = 'foo';

for(let element of arr) {
  console.log(element);
}

for(let element in arr) {
  console.log(element);
}

@Murtuza Husain 2017-11-11 06:16:27

The lambda syntax doesnt usually work in IE 10 or below.

I usually use the

[].forEach.call(arrayName,function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});


If you are a jQuery Fan and already have a jQuery file running, you should reverse the positions of the index and value parameters

$("#ul>li").each(function(**index,value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

@Nouman Dilshad 2018-07-17 12:30:51

You can call forEach Like this:

let Array = [1,3,2];

theArray.forEach((element)=>{ 
  // use the element of the array
  console.log(element) 
}

element will have the value of each index from 0 to the length of the array.

Output:

1    
3    
2

Explaination:

forEach is in prototype class. you can also call this as theArray.prototype.forEach(...);

prototype: https://hackernoon.com/prototypes-in-javascript-5bba2990e04b

You can also alterate over an array like this:

for(let i=0;i<theArray.length;i++){
  console.log(i); //i will have the value of each index
}

@BlackBeard 2018-07-06 07:11:14

If you have a massive array you should use iterators to gain some efficiency. Iterators are a property of certain JavaScript collections (like Map, Set, String, Array). Even, for..of uses iterator under-the-hood.

Iterators improve efficiency by letting you consume the items in a list one at a time as if they were a stream. What makes an iterator special is how it traverses a collection. Other loops need to load the entire collection up front in order to iterate over it, whereas an iterator only needs to know the current position in the collection.

You access the current item by calling the iterator’s next method. The next method will return the value of the current item and a boolean to indicate when you have reached the end of the collection. The following is an example of creating an iterator from an array.

Transform your regular array to iterator using values() method like this:

    const myArr = [2,3,4]

let it = myArr.values();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

You can also transform your regular array to iterator using Symbol.iterator like this:

const myArr = [2,3,4]

let it = myArr[Symbol.iterator]();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

You can also transform your regular array to an iterator like this:

let myArr = [8, 10, 12];

function makeIterator(array) {
    var nextIndex = 0;
    
    return {
       next: function() {
           return nextIndex < array.length ?
               {value: array[nextIndex++], done: false} :
               {done: true};
       }
    };
};

var it = makeIterator(myArr);

console.log(it.next().value);   // {value: 8, done: false}
console.log(it.next().value);   // {value: 10, done: false}
console.log(it.next().value);   // {value: 12, done: false}
console.log(it.next().value);   // {value: undefined, done: true}

NOTE:

  • Iterators are exhaustible in nature.
  • Objects are not iterable by default. Use for..in in that case because instead of values it works with keys.

You can read more about iteration protocol here.

@John 2018-01-11 18:03:37

var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})

@Jasper 2018-01-12 08:29:07

This adds nothing.

@Alireza 2017-05-10 14:32:02

There are a few ways to loop through an array in JavaScript, as below:

for - it's the most common one. Full block of code for looping

var languages = ["JAVA", "JavaScript", "C#", "Python"];
var i, len, text;
for (i = 0, len = languages.length, text = ""; i < len; i++) {
    text += languages[i] + "<br>";
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

while - loop while a condition is through. It seems to be the fastest loop

var text = "";
var i = 0;
while (i < 10) {
    text +=  i + ") something<br>";
    i++;
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

do/while - also loop through a block of code while the condition is true, will run at least one time

var text = ""
var i = 0;
do {
    text += i + ") something <br>";
    i++;
}
while (i < 10);
document.getElementById("example").innerHTML = text;
<p id="example"></p>

Functional loops - forEach, map, filter, also reduce (they loop through the function, but used if you need to do something with your array, etc.

// For example, in this case we loop through the number and double them up using the map function
var numbers = [65, 44, 12, 4];
document.getElementById("example").innerHTML = numbers.map(function(num){return num * 2});
<p id="example"></p>

For more information and examples about functional programming on arrays, look at the blog post Functional programming in JavaScript: map, filter and reduce.

@Nik Kyriakides 2018-01-03 15:40:24

Small correction: forEach is not a "functional" loop since it doesn't return a new Array (actually it doesn't return anything), it just iterates.

@Volkan Seçkin Akbayır 2015-08-28 07:27:21

I also would like to add this as a composition of a 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 won't need to be declared later with another line. It is handy when looping trough the object array.

Cons:

This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. And also depending on browser it can be "not" optimized to work faster than original one.

@Ante Jablan Adamović 2017-11-09 15:31:44

A way closest to your idea would be to use Array.forEach() which accepts a clojure function wich will be executed for each element of the array.

myArray.forEach(
  (item) => {
    // do something 
    console.log(item);
  }
);

Another viable way would be to use Array.map() which works in the same way but also mutates each element and returns it like:

var myArray = [1, 2, 3];
myArray = myArray.map(
  (item) => {
    return item + 1;
  }
);

console.log(myArray); // [2, 3, 4]

@Jesús Franco 2018-05-14 23:23:11

This is wrong, map does not mutates the elements of the array, because it returns a new array, with the items of that new one being the result of applying the function to the items of the old array.

@Anil Kumar Arya 2017-04-09 16:51:51

ECMAScript5 (the version on Javascript) to work with Arrays.

forEach - Iterates through every item in the array and do whatever you need with each item.

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is the #" + (index+1) + " in musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

In case , more interested on operation on array using some inbuilt feature.

map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

reduce - As the name says it reduces the array to a single value by calling the given function passing in the currenct element and the result of the previous execution.

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

every - Returns true or false if all the elements in the array pass the test in the callback function.

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];  
ages.every(function(elem) {  
  return elem >= 18;
});

// Output: false

filter - Very similar to every except that filter return an array with the elements that return true to the given function.

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]

Hope this will be useful.

@joeytwiddle 2014-05-02 14:21:19

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.

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.

@joeytwiddle 2014-05-02 15:14:43

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!

@Kabb5 2015-05-15 16:32:51

How about this for a reverse loop? var i= array.length; while(i--) { ...

@joeytwiddle 2018-02-10 06:41:34

The same answer is given much more concisely here (on a different question).

@Zaz 2016-05-26 16:14:44

As of ES6:

list = [0, 1, 2, 3]
for (let obj of list) {
    console.log(obj)
}

Where of avoids the oddities associated with in and makes it work like the for loop of any other language, and let binds i within the loop as opposed to within the function.

The braces ({}) can be omitted when there is only one command (e.g. in the example above).

@Priyanshu Chauhan 2015-07-27 07:07:27

There's no inbuilt ability to break in forEach. To interrupt execution use the Array#some like below:

[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, returns true, short-circuiting the execution of the rest. Original Answer see Array prototype for some

@Tim 2014-01-30 15:25:53

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 = [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.

@Poonam 2012-02-17 14:01:07

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].
}

@mopsyd 2013-09-04 16:01:04

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.

@Kevin Boss 2013-10-07 13:04:05

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

@Noe 2013-10-09 19:38:59

Refrain from using jQuery when you can use vanilla js

@Steve K 2014-12-10 06:48:28

Stick to standard JS, keep the 3rd party libraries out of the answer unless there isn't a native language solution

@Ajedi32 2015-01-02 19:40:23

Kind of reminds me of this: i.stack.imgur.com/ssRUr.gif

@Micka 2013-07-17 09:07:04

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

@user2359695 2014-06-20 22:56:52

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.

@gaby de wilde 2013-03-10 02:37:51

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.

@M. Grzywaczewski 2016-08-04 01:14:12

It doesn't work if you happen to have a sparse array like [1, 2, undefined, 3].

@joeytwiddle 2017-11-06 13:19:21

... or indeed anything falsey: [1, 2, 0, 3] or [true, true, false, true]

@Daniel W. 2014-04-01 11:15:26

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

@user663031 2016-09-30 03:37:45

I think the output is more likely to be [undefined, 2, undefined, 4, undefined, 6, undefined].

@Rajesh Paul 2013-12-25 16:14:31

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

@Rajesh Paul 2014-02-15 04:05:12

Console log is just for the demo. That's to make it a cmplete running example.

@Federico Piragua 2013-11-02 02:23:32

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

@nmoliveira 2013-04-10 00:26:36

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
  }
);

@MIdhun Krishna 2013-12-18 09:47:27

iterator in this, is doing a needless length calculation. In an ideal case, the list length should be calculated only once.

@nmoliveira 2013-12-18 12:36:09

@MIdhunKrishna I updated my answer and the jsFiddle but be aware that it is not as simple as you think. Check this question

@marciowb 2016-10-06 19:45:19

The full and right implementation can be found here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Related Questions

Sponsored Content

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5774631 View
  • 7205 Score
  • 79 Answer
  • Tags:   javascript arrays

36 Answered Questions

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

39 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

41 Answered Questions

[SOLVED] Sort array of objects by string property value

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

26 Answered Questions

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

21 Answered Questions

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

  • 2009-05-28 16:18:14
  • edt
  • 1485475 View
  • 1435 Score
  • 21 Answer
  • Tags:   javascript

Sponsored Content