2

I am able to insert a value at an arbitrary index outside of the bounds of the array like so.

> const a = []
undefined
> a[999] = true
true
> a
[ <999 empty items>, true ]

I suspect that v8 is not creating 999 empty items under the hood and Arrays work more like Objects and instead we are creating a hidden class which has one key which is the key 999 at offset 0. Is this correct?

david_adler
  • 9,690
  • 6
  • 57
  • 97
  • 1
    I'm pretty certain that v8 does not use hidden classes for integer-index properties. – Bergi Apr 07 '20 at 10:18
  • 2
    An array is an *object*. And objects in JS are key-value hashes/dictionaries. So when you do `a[999] = true` you set the key `999` to `true`. That's what happens. Not much different from `{ 999: true }`. An array isn't a contiguous memory location. The name is honestly a bit of a misnomer. Arrays *are* treated slightly differently and part of that is expecting to have slots up to `999`. But it's safe to treat that as a display quirk. – VLAZ Apr 07 '20 at 10:23
  • 2
    @DavidsaysreinstateMonica the length would be `1000` but like the name "array", the name of the property "length" is also a bit of a misnomer. It's more of a "next available index". The difference is apparent with sparse arrays. – VLAZ Apr 07 '20 at 10:25
  • @VLAZ "*An array isn't a contiguous memory location*" - it is implemented and used as one, though. I think this question is asking for the specifics of the V8 implementation. If it was just about how arrays work in JS and what `[ <999 empty items>, true ]` means, it should have been closed as a duplicate of https://stackoverflow.com/q/10683773/1048572. – Bergi Apr 07 '20 at 10:54

1 Answers1

1

From https://v8.dev/blog/fast-properties

Arrays [] and Objects {} are both JSObjects.

The difference is that array-indexed items populate the elements store. Adding array-indexed properties does not create a new HiddenClass.

In sparsely populated arrays like arr[9999] = 'foo' v8 creates a "custom descriptor" in "dictionary mode" to avoid the memory waste of creating 10k empty entries. Array operations in dictionary mode will be significantly slower than contiguous arrays.

david_adler
  • 9,690
  • 6
  • 57
  • 97