4040

In Java, you can use a for loop to traverse objects in an array as follows:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

Can I do the same in JavaScript?

10
  • 8
    Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct? Commented Jun 10, 2010 at 0:15
  • 55
    no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended... Commented Jun 10, 2010 at 0:38
  • 7
    related - stackoverflow.com/questions/5349425/… Commented Nov 1, 2011 at 17:53
  • 9
    jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays Commented Nov 3, 2016 at 19:45
  • 15
    @CMS No, it's not really simple. It's really simple in every other language. It's ridiculously complex in JS, where you have in and of that can both be used and do different things. Then you also have forEach and the ugly and annoying index based looping. Every other modern language makes looping over a collection easy and straightforward with no surprises or confusion. JS could, too, but it doesn't.
    – jpmc26
    Commented Oct 5, 2018 at 15:59

46 Answers 46

1
2
10

The formal (and perhaps old) way is Array.prototype.forEach(...):

var arr = ["apple", "banana", "cherry", "mango"];
arr.forEach(function(item, index, _) {
   console.log("[" + index + "] = '" + item + "'");
});
1
  • your "some code" should have had an example in it. It isn't entirely clear if the variables are passed in directly or as "this" or whatever.
    – John Lord
    Commented Oct 23, 2020 at 16:17
9
var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
    console.log(i,j);
}

A lot cleaner...

1
  • That's not very clean compared to z.forEach(j => console.log(j));. Commented Mar 17, 2020 at 14:57
9
var myStringArray = ["hello", "World"];
myStringArray.forEach(function(val, index){
   console.log(val, index);
})
0
9

Short answer: yes. You can do with this:

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

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

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

9
//Make array
var array = ["1","2","3","4","5","6","7","8","9","10"]
//Loop
for(var i = 0; i < array.length; i++){
 console.log((i+1) + " --> " + array[i])
}

For the ACTUAL number for i, you need to change (i+1) to i or (i), if you want.
Hope this helped.

8

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

var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
    // Do something
})
1
  • 3
    This exact functionality is already part of Mark Reed's answer.
    – user513951
    Commented Dec 12, 2015 at 3:27
7

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

_.forEach([1, 2], (value) => {
  console.log(value);
});
6

Just a simple one-line solution:

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

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

2
  • 4
    You'd rather want to use .forEach() and drop the return e; Commented Oct 6, 2017 at 11:09
  • 3
    as map implies, the function map is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.
    – marpme
    Commented Nov 17, 2017 at 22:28
6

Array traversal cheatsheet in JavaScript

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

1. Classic for loop

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

for (let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

2. for...of

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

for (const item of myArray) {
  console.log(item);
}

3. Array.prototype.forEach()

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

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

4. while loop

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

while (i < myArray.length) {
  console.log(myArray[i]);
  i++;
}

5. do...while loop

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

do {
  console.log(myArray[i]);
  i++;
} while (i < myArray.length);

6. Queue style

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


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

7. Stack style

Note: The list is printed reverse in this one.

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

while (myArray.length) {
  console.log(myArray.pop());
}

1
  • "for" and "for in" loops create extra variable, "forEach" - create extra function context. I think the best way is "for of". Commented Jun 17, 2021 at 7:43
6

There are multiple ways to do it in javascript. Here are the common ways of handling arrays.

Method 1:

const students = ["Arun","Jos","John","Kiran"]
for (var index = 0; index < students.length; index++) {
  console.log(students[index]);
}

Method 2:

students.forEach((student, index) => console.log(student));

Method 3:

for (const student of students) {
      console.log(student);
}
  
4

Well, how about this:

for (var key in myStringArray) {
    console.log(myStringArray[key]);
}
3
  • 11
    for/in loops are discouraged for array enumeration, as the order of eumeration is not guaranteed, and it enumerates properties, not just array elements. For more info, see stackoverflow.com/questions/500504/…, or even the accepted answer of this question; stackoverflow.com/a/3010848/444991
    – Matt
    Commented May 9, 2014 at 14:25
  • well, thanks for the update.. and what about the situation when we don't care about the order of the array? Will this still be discouraged? Commented May 9, 2014 at 14:32
  • 5
    It'll still be discouraged because it enumerates all the properties, not just the array elements. The two posts I linked to explain this in more detail.
    – Matt
    Commented May 9, 2014 at 14:35
4
var obj = ["one","two","three"];

for(x in obj){
    console.log(obj[x]);
}
0
4

It is better to use a sequential for loop:

for (var i = 0; i < myStringArray.length; i++) {
    // Do something
}
1
  • 2
    Why is it better? of course, you can do that in java as well, bu he asked about a foreach loop. Commented Sep 27, 2019 at 18:55
2

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

2
  • 4
    Was it really necessary to bring jQuery or HTML into this? Commented Mar 5, 2019 at 22:46
  • 2
    @domdambrogia: It is a meme. Commented Oct 30, 2020 at 8:28
-1

Consider this:

const ITEMS = ['One','Two','Three']
let item=-1

//Then, you get looping with every call of:

ITEMS[item=item==ITEMS.length-1?0:item+1]
-1

This answer provides an alternative to loops and array functions to iterate through an array.

In some cases it makes sense to use a recursive implementation over conventional loops and callbacks. Particularly, if you have to work with multiple arrays or nested arrays. You avoid writing nested loops to access data from multiple arrays. I also find this code easier to read and write.

/**
  array is the array your wish to iterate. 
  response is what you want to return.
  index increments each time the function calls itself.
**/

const iterateArray = (array = [], response = [], index = 0) => {
    const data = array[index]

    // If this condition is met. The function returns and stops calling itself.
    if (!data) {
      return response
    }
    // Do work...
    response.push("String 1")
    response.push("String 2")

    // Do more work...

    // THE FUNCTION CALLS ITSELF
    iterateArray(data, response, index+=1)
}

const mainFunction = () => {
    const text = ["qwerty", "poiuyt", "zxcvb"]

    // Call the recursive function
    const finalText = iterateArray(text)
    console.log("Final Text: ", finalText()
}

Say the array being passed to iterateArray contained objects instead of strings. And each object contained another array in it. You would have to run nested loops to access the inner array, but not if you iterate recursively.

You can also make iterateArray a Promise.

const iterateArray = (array = [], response = []) =>
  new Promise(async (resolve, reject) => {
    const data = array.shift()
    // If this condition is met, the function returns and stops calling itself.
    if (!data) {
      return resolve(response)
    }

    // Do work here...

    const apiRequestData = data.innerArray.find((item) => {
      item.id === data.sub_id
    })

    if (apiRequestData) {
      try {
        const axiosResponse = await axios.post(
          "http://example.com",
          apiRequestData
        )
        if (axiosResponse.status === 200) {
          response.push(apiRequestData)
        } else {
          return reject("Data not found")
        }
      } catch (error) {
        reject(error)
      }
    } else {
      return reject("Data not found")
    }
    // THE FUNCTION RESOLVES AND CALLS ITSELF
    resolve(iterateArray(data, response))
  })

1
2

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