Search code examples
javascriptloopsfor-in-looplanguage-specifications

Why is the variable in a for...in loop a string?


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?


Solution

  • for..in calls EnumerateObjectProperties, which does:

    Return an Iterator object (26.1.1.2) whose next method iterates over all the String-valued keys of enumerable properties of O. The iterator object is never directly accessible to ECMAScript code. The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

    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 like Object.keys or Object.getOwnPropertyNames). You can also see [[OwnPropertyKeys]](), which says:

    The Type of each element of the returned List is either String or Symbol.

    For example, with Array.prototype.push, you can see:

    5. For each element E of items, do:
      a. Perform ? Set(O, ! ToString(len), E, true).
    

    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.