I was using for...in loops to log values, and I noticed that the variable in a for...in loop (i
, in this case) is a string.
for (var i in ['a', 'b', 'c']) {
console.log(i, typeof i)
}
I searched the ECMAScript specifications, in the section titled "The for-in, for-of, and for-await-of Statements", for any information on this, but could not find anything on this.
My question is, is there anything in the spec about this, and if not, why is it a string?
for..in calls EnumerateObjectProperties, which does:
All object properties are either strings or symbols. Even properties on arrays which can be set and retrieved as if they were numbers are interpreted as strings (and retrieved as strings when retrieved via
for..in
or other property enumeration methods likeObject.keys
orObject.getOwnPropertyNames
). You can also see[[OwnPropertyKeys]]()
, which says:For example, with
Array.prototype.push
, you can see:Property assignment always results in setting a property which is either a string or a symbol. (See
isPropertyKey
- If Type(argument) is String, return true. If Type(argument) is Symbol, return true. Otherwise Return false.