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.


@mojtaba ramezani 2020-01-27 06:53:37

using grep function in jquery, for example:

$.grep( [ 0, 1, 2 ], function( n, i ) {
    return n > 0;

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

You can call forEach like this:

forEach will iterate over the array you provide and for each iteration it will have element which holds the value of that iteration. If you need index you can get the current index by passing the i as the second parameter in the callback function for forEach.

Foreach is basically a High Order Function, Which takes another function as its parameter.

let theArray= [1,3,2];

theArray.forEach((element) => {
  // Use the element of the array



You can also iterate over an array like this:

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

@ankitkanojia 2020-01-22 08:14:04

As per new updated feature ECMAScript 6(ES6) and ECMAScript 2015, you can use following options with loops

for loops

for(var i = 0; i < 5; i++){

//output: 0,1,2,3,4 loops

let obj = {"a":1, "b":2}

for(let k in obj){

//output: a,b


let array = [1,2,3,4]

array.forEach((x) => {

//output: 1,2,3,4

for...of loops

let array = [1,2,3,4]

for(let x of array){

//output: 1,2,3,4

while loops

let x = 0

while(x < 5){

//output: 1,2,3,4

do...while loops

let x = 0

}while(x < 5)

//output: 1,2,3,4

@vkarpov15 2019-12-23 19:31:19

I'd argue that for/of is the way to go:

const arr = ['a', 'b', 'c'];

for (const v of arr) {
  console.log(v); // Prints "a", "b", "c"
  • Unlike for/in, for/of skips non-numeric properties on the array. For example, if you set = 'test', for (var v in arr) will loop through the 'foo' key.

  • Unlike forEach(), for/of doesn't skip "holes" in arrays. const arr = ['a',, 'c'] is valid JavaScript, just the 2nd element is a "hole". The array is functionally equivalent to ['a', undefined, 'c'].

You can read more in this blog post on for/of vs forEach().

@Kamil Kiełczewski 2019-12-18 17:09:58


Today 18.12.2019 I perform test on my MacOs HighSierra 10.13.6, on Chrome v 79.0, Safari v13.0.4 and Firefox v71.0 (64 bit) - conclusions about optimisation (and micro-optimisation usually not worth to introduce it to code because benefit is small but code complexity grows).

  • It looks like the traditional for (Aa) is good choice to write fast code on all browsers.

  • The other solutions like for-of (Ad), all in group C.... are usually 2x-10x (and more) times slower than Aa, but for small arrays is ok to use it - in sake of increase code clarity.

  • The loops with array length cached in n (Ab, Bb, Be) are sometimes faster, sometimes not. Probably compilers automatically detect this situation an introduce caching. The speed differences between cached and no-cached versions (Aa, Ba, Bd) are about ~1% - so it looks like introduce n is micro-optimisation.

  • The i-- like solutions where loop start from last array element (Ac, Bc) are usually ~30% slower than forward solutions - probably the reason is the the way of CPU memory cache working - forward memory reading is more optimal for CPU cacheing). Is recommended to NOT USE such solutions.


In tests we calc sum of array elements. I perform test for small arrays (10 elements) and big arrays (1M elements) and divide them into 3 groups:

  • A - for tests
  • B - while tests
  • C - other/alternative methods

let arr=[1,2,3,4,5,6,7,8,9,10];
//let arr = Array.from(Array(1000000), (x,i)=> i%10);

function Aa(a,s=0) { 
  for(let i=0; i<a.length; i++) { s+= a[i]; } 

function Ab(a,s=0) { 
  let n= a.length;
  for(let i=0; i<n; i++) { s+= a[i]; } 

function Ac(a,s=0) { 
  for(let i=a.length; i--;) { s+= a[i]; } 

function Ad(a,s=0) {
  for(let x of a) { s+=x; }

function Ae(a,s=0) {
  for(let i in a) if (a.hasOwnProperty(i)) { s+=a[i]; }

function Ba(a,s=0) {
  let i= -1;
  while(++i < a.length) { s+= a[i]; }

function Bb(a,s=0) {
  let i= -1; let n= a.length;
  while(++i < n) { s+= a[i]; }

function Bc(a,s=0) {
  let i=a.length;
  while(i--) { s+= a[i]; }

function Bd(a,s=0) {
  let i=0;
  do { s+= a[i] } while (++i < a.length);

function Be(a,s=0) {
  let i=0; let n=a.length;
  do { s+= a[i] } while (++i < n);

function Bf(a,s=0) {
  const it = a.values(); let e;
  while (!(e = { s+= e.value; }  

function Ca(a,s=0) { => { s+=x });

function Cb(a,s=0) {
  a.forEach(x => { s+=x });

function Cc(a,s=0) {
  a.every(x => (s+=x,1) );

function Cd(a,s=0) {
  a.filter(x => { s+=x } );

function Ce(a,s=0) {
  a.reduce( (z,c) => { s+=c }, 0 );

function Cf(a,s=0) {
  a.reduceRight( (z,c) => { s+=c }, 0 );

function Cg(a,s=0) {
  a.some(x => { s+=x } );

function Ch(a,s=0) {
  Array.from(a, x=> s+=x);



<p style="color: red">This snippets only PRESENTS code used for benchmark - it not perform test itself</p>

Cross browser results

Results for all tested browsers

enter image description herebrowsers**

Array with 10 elements

Results for Chrome. You can perform test on your machine here

enter image description here

Array with 1.000.000 elements

Results for Chrome. You can perform test on your machine here

enter image description here

@Mustafa Kunwa 2019-12-19 12:26:01

You can use: 1. ForEach

theArray.forEach(function (array, index) {


for(var i=0;i<theArray.length;i++){
} => console.log(x));

theArray.filter(x => console.log(x));

And there are many others for iteration

@antelove 2019-12-14 10:24:50

Mozilla Docs

/* get all form */
document.querySelectorAll( "form" ).forEach( form => {
  /* each form add onsubmit event */
  form.addEventListener( "submit", event => {
    event.preventDefault(); // return false

    /* display it */
  } );

} );
<form action="form1.php" >
  <input type="submit" value="Submit" />
<form action="form2.php" >
  <input type="submit" value="Submit" />
<form action="form3.php" >
  <input type="submit" value="Submit" />

@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>";
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>";
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 they are 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 ={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.

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


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


  • 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 was better to use forEach()

In general for higher level code where clarity and safety are greater concerns, I previously recommended using Array::forEach as your default pattern for looping (although these days I prefer to use for..of). Reasons to prefer forEach over a reverse loop are:

  • It is clearer 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.)

It is now even better to use for..of!

There is a debate about whether for..of or forEach() are preferable:

  • For maximum browser support, for..of requires a polyfill for iterators, making your app slightly slower to execute and slightly larger to download.

  • For that reason (and to encourage use of map and filter), some front-end style guides ban for..of completely!

  • But the above concerns is not applicable to Node.js applications, where for..of is now well supported.

  • And furthermore await does not work inside forEach(). Using for..of is the clearest pattern in this case.

Personally, I tend to use whatever looks easiest to read, unless performance or minification has become a major concern. So these days I prefer to use for..of instead of forEach(), but I will always use map or filter or find or some when applicable. (For the sake of my colleagues, I rarely use reduce.)

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.


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!

@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 ECMAScript 6:

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

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

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

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

  (item) => {
    // Do something

Another viable way would be to use which works in the same way, but it also takes all values that you return and returns them in a new array (essentially mapping each element to a new one), like this:

var myArray = [1, 2, 3];
myArray =
  (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.

@Ante Jablan Adamović 2019-09-04 06:58:30

I never said it doesn't return a new array, I was referring to the change applied by the function. But here I'll change it in the answer.

@Jesús Franco 2019-09-04 17:36:29

again wrong, map does not modify or mutates at all the items in the original array, I've proposed and edit to the answer emphasizing map works with a copy of the original items, leaving the original array untouched at all

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

ECMAScript 5 (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 #" + (index+1) + " in the 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 current 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 returns an array with the elements that return true to the given function.

// Finding the even numbers
  return (elem % 2 == 0)

// Output: [2,4,6]

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

The lambda syntax doesn't usually work in Internet Explorer 10 or below.

I usually use the

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

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


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

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

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


    for..of loop

In JavaScript there are many ways of accomplishing both of these goals. However, some are more convenient than others. Below you can find some commonly used methods (the most convenient 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 =, index, array) => {
  return element * 2;


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 explicitly manipulate it with thinks like splice).

Also note that the map function's callback provides the index number of the current iteration as a second argument. 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) {
  // index, and oldArray are provided as 2nd and 3th argument by the callback



Just like the map function, the forEach callback provides the index number of the current iteration as a second argument. 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. Note 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 loop with the for..of loop. 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]; = 'foo';

for(let element of arr) {

for(let element in arr) {

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

Using loops with ECMAScript 6 destructuring and the spread operator

Destructuring and using of the spread operator have proven quite useful for newcomers to ECMAScript 6 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 the for...of statement and the .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) {

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 =, 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 parentheses
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']

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

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

I come from Python, and I found this way much clearer.

theArray being the array, and instance being the elements of the array:

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


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

compare to:

theArray.forEach(function(instance) {

But at the end of the day both are doing the same thing.

@Rusty 2019-07-03 07:53:23

It returns index, not object instances

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

// Looping through arrays using the foreach ECMAScript 6 way

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

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

If you want to keep your code in the functional way, use map: => do_something);

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

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

If you want to loop through an array of objects with the arrow function:

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

  console.log('I am ' + + ' and I am ' + person.age + ' old');

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

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

See Arrays in JavaScript: Part 2.

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

Note: 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 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 Hoffmann 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).

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


  • 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+)


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

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

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

And/or counting backward:

var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --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 {
} catch (e) {
    console.error(e);   // "ReferenceError: index is not defined"
try {
} 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);

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

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 (, key) &&
            rexNum.test(key) &&
            index <= 4294967294
            ) {
  , 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) {

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 = {

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:, 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..., 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 =;

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

    var divs ="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 =; 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()

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

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

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

@s3c 2019-10-29 14:30:07

An awesomely long, useful and detailed answer, kudos! Given that ECMA10 was already released in June 2019, might you update (add on) the entire answer where it fits in that same style of yours? Although I would appreciate not to delete anything out 'cause this has to be to best answer I ever read on SO.

@T.J. Crowder 2019-10-29 14:34:18

@s3c - Thanks! I don't think additions in ES2019 (or the likely contents of ES2020) relate to the above, though. I can't think of a new array / iterable looping feature being added in them, so I don't think there's any need to update the answer...?

@s3c 2019-10-29 14:51:37

OK, perhaps I meant for you to elaborate on even more specific cases where mapping is appropriate (faster, less consuming), but I clearly don't know nearly enough on the matter, let alone compared to you. So thanks again and just leave the answer as is by all means. Google will return those answers somewhere anyway :)

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

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

theArray.forEach ( element => {

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

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

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


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

const myArr = [2,3,4]

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


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(;   // {value: 8, done: false}
console.log(;   // {value: 10, done: false}
console.log(;   // {value: 12, done: false}
console.log(;   // {value: undefined, done: true}


  • Iterators are exhaustible in nature.
  • Objects are not iterable by default. Use 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.

@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];) {


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.


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.

@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++) 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'p'), "this.className = data;",'blue');

Each p tag gets class="blue"

Example #3'p'), 
    "if( i % 2 == 0) this.className = data;",

Every other p tag gets class="red">

Example #4''), 
    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


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.

@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

@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

Related Questions

Sponsored Content

94 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 6267047 View
  • 7826 Score
  • 94 Answer
  • Tags:   javascript arrays

48 Answered Questions

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

45 Answered Questions

[SOLVED] Sort array of objects by string property value

43 Answered Questions

[SOLVED] Loop through an array in JavaScript

27 Answered Questions

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

42 Answered Questions

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

39 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

4 Answered Questions

7 Answered Questions

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

Sponsored Content