-2

Can you explain me, please, why first console.log shows me array with both: array.foo and item, but when I use for of loop it does not show array.foo?

let array = [3,5,8, item = 'good'];
array.foo = 'hello';
console.log(array);

for (var i of array) {
 console.log( i);
}
KingOfLeon
  • 35
  • 7
  • 1
    because, although both `item` and `foo` are _properties_ of `array`, they are not _enumerable properties_ – Hamms May 26 '16 at 22:29
  • the `for (var variable of array){}` syntax with arrays only loops over the numeric indices, not the properties of the array object – shamsup May 26 '16 at 22:31
  • 1
    @Hamms: `item` is a variable. `'good'` is an array element (and the value of an enumerable property that will be iterated). `.foo` is an enumerable property that does not get iterated because it's not an array index. – Bergi May 26 '16 at 22:33

1 Answers1

1

The for-of runtime semantics tell us that we will iterate over ForIn/OfHeadEvaluation( « », AssignmentExpression, iterate). Which in turn returns us the GetIterator(exprValue) (see 8.b). GetIterator returns an iterator from the @@iterator slot (or Symbol.iterator). Which for an array returns the Array.prototype.values which uses CreateArrayIterator whose semantics are defined here.

And as you can see at %ArrayIteratorPrototype%.next( ) it iterates through the indexes from 0 through length - 1 and says nothing about other properties.

So, to summarise, the for-of does not iterate through non-index properties because the array iterator does not do so.

zerkms
  • 230,357
  • 57
  • 408
  • 498