What does arr.foo="hello" do in the example?

That’s because 99% of the times you won’t need to set the property of an array, since their sole purpose in life is to be iterated over and used as a linear in-memory data structure.

The purpose of that code you posted is to teach newcomers to the language about the fact that an array is just an object whose keys are numbers from 0 to 4.28 billion (according to the language Spec).

image

The for…in loop iterates over the enumerable keys of any object; in this case, the indices are the keys inside an array but you can also set your own key-value pairs inside an array (even if it’s not every useful most of the time); if you do, they will appear in a for…in loop, in an Object.keys (or their values including custom key-VALUE pairs with Object.values), and if you do arr.hasOwnProperty('foo') //> true.

The for…of loop only works in iterables/iterators such as:

  • Array
  • String
  • Set
  • Map
  • Generators
  • Async Generators (with for await)

And since the only iterable values are those that have indices, you’ll get the expected result.

image

In summary, it’s just one of those quirky things that JS has that should not even be toyed with unless you have no other choice, which in my opinion would be a design flaw anyway to set a custom property to an array. If you want custom properties and/or methods you’re better off either modifying the array prototype itself which is still not recommended or creating a custom data structure on top of the array such as Stack, Queue, etc.

1 Like