Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I understand that the basic for…in syntax in JavaScript looks like this:

for (var obj in myArray) {

    // ...

}

But how do I get the loop counter/index?

1 Answer

0 votes
by (13.1k points)

for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

for in iterates over property names and does so in an unspecified order. You should not use it to iterate over arrays. For them, there is ES5’s forEach method that passes both the value and the index to the function you give it.

var myArray = [12, 15, 18, 32];

myArray.forEach(function (value, i) {

    console.log('%d: %s', i, value);

});

Outputs:

0: 12

1: 15

2: 18

3: 32

Or you can use ES6’s Array.prototype.entries, which now has support across current browser versions:

for (const [i, value] of myArray.entries()) {

    console.log('%d: %s', i, value);

}

Want to be a Full Stack Developer? Check out the Full Stack Developer course from Intellipaat.

Browse Categories

...