Why is Key a String in JavaScript for…in Loop

for-loopjavascript

I'm writing a simple for...in loop in javascript, and wondering why the key is a string and not a number?

Why is it so, and can I change that to be a number?

var array = ["a", "b", "c"];

for (var key in array) {
   console.log(typeof key); //string
   console.log(key + 1); //expected output : 01, 11, 21...
}

Best Answer

It's a string because standard arrays in JavaScript aren't really arrays at all¹, they're objects with properties for the array entries, and object property names (keys) are strings, Symbols, or (soonish) private names.

You can't make it a number by default in a for-in, but you can convert it to a number, or use other forms such as a standard for or a forEach call:

for (var key = 0; key < array.length; ++k) {
    // ...
}
// ..or
array.forEach((entry, key) => {
    // ...
});

Using for-in to loop through an array is almost always an anti-pattern. See my answer here for a thorough rundown of your various options for looping through arrays.


¹ That's a post on my anemic little blog.

Related Question