1

A strange behavior of array assignment at index: array[<some string>]. Let's say I have a normal array:

const arr = [1, 2, 3]; // undefined

If I type:

arr['.'] = 4; // 4
arr // (3) [1, 2, 3, .: 4]
arr.length // 3
for (a of arr) {
  console.log(a)
  // 1
  // 2
  // 3
}

Now I get some strange hybrid between an array and an object. If I try to spread the array into another variable:

const barr = [...arr] // (3) [1, 2, 3]

Does anyone know what is going on and what rules create this kind of behavior?

MaxG
  • 1,079
  • 2
  • 13
  • 26
  • 2
    Arrays are always objects. It just doesn’t usually make sense to put non-array-element properties on them. You can do the same with functions and dates, maps and sets, anything mutable. – Ry- Jul 25 '19 at 23:21
  • @Ry- What does this mean "Arrays are always objects"? How does an array implement this assignment? Are there any docs? – MaxG Jul 25 '19 at 23:32
  • 1
    Check out https://stackoverflow.com/questions/5048371/are-javascript-arrays-primitives-strings-objects – CertainPerformance Jul 25 '19 at 23:37
  • 1
    Everything is an object* in JavaScript. You can try to assign properties to any value. You can call methods on any value. etc. (* not actually everything, and this is an oversimplification) – Ry- Jul 25 '19 at 23:37
  • @Ry- How is this a duplicate? `[...arr]` and `of` depend on the array's iterator; the length has nothing to do with it. – AuxTaco Jul 25 '19 at 23:40
  • @AuxTaco: The main idea that the additional properties aren’t actually part of the array is the same. – Ry- Jul 25 '19 at 23:41
  • @Ry- this is a duplicate of another question. Not the one you've mentioned, but the one CertainPerformance did. Read the question again. – MaxG Jul 25 '19 at 23:42

0 Answers0