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

Hello everyone. Today I am learning the difference between for in and for of in JS.
The example is listed here


let arr = [3, 5, 7];
arr.foo = "hello";

for (let i in arr) 
{console.log(i)} // expected value  0,1,2,foo

for (let i of arr) 
{ console.log(i)} // expected 3,5,7

I am not sure what does arr.foo = “hello” do in this example. I have googled and search the mdn but still can’t find anything related to the usage of arr.foo or .foo.

can anyone kindly explain to me what is arr.foo = “hello” ? And why didn’t the hello print out in for (let i of arr) { console.log(i)}?

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