1

I want to understand if there exists a list/Array in JavaScript as opposed to an Array like Object. If there are some resources or info on this I would love that.

So to my understanding, arrays in JavaScript are just objects with the index of the array being a key in the object. But objects are hash maps correct? In which case hash maps takes a key, hashes it to a index and then stores that value at the index in a list/array. This way if we ever need to access a key in the object, we can easy hash the key and go to the array to access the value in constant time. But arrays don't really exist in JavaScript, so is there some array/list like data structure under the hood in JavaScript that we just don't have access to?

  • 1
    No. JavaScript arrays are JavaScript objects, that's true. But how these are represented under the hood is decided by the engine implementation, they could be arrays, hash maps, or records. (And usually are, for performance optimisation reasons). – Bergi Aug 21 '19 at 21:50
  • possible duplicate of [How are JavaScript arrays represented in physical memory?](https://stackoverflow.com/q/20321047/1048572) – Bergi Aug 21 '19 at 22:12

1 Answers1

4

JavaScript is an interpreted language. You could write a valid JS engine in many different languages, and thus the specification itself provides a very abstract memory model. That means that objects are A collection of key-value pairs that provide ways to access these pairs, and arrays are exotic objects, that treat numeric keys differently. That's it, the specification doesn't define anything else, thus how this is actually represented in the memory is totally up to the engine.

You are right though that it really makes sense to implement objects as hashtables internally (in some situations), and arrays as real arrays or lists. Most engines use different underlying implementations depending on the way you use the objects / arrays though.

Worth reading:

Element kinds in v8

Fast properties in v8

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Arrays don't really have numbers as keys. Keys are still only strings or symbols. Arrays are just exotic objects that treat [some (numeric) strings](https://stackoverflow.com/q/27537677/1048572) specially. – Bergi Aug 21 '19 at 21:57
  • Also, I doubt arrays are represented as linked lists. Did you mean arraylists/vectors? – Bergi Aug 21 '19 at 21:58
  • @Bergi ah right, thats one of the design decisions I never understood ... and yeah, that statement is quite a vague claim, better to remove it – Jonas Wilms Aug 21 '19 at 21:58
  • 1
    I would guess it just emerged from the principles "everything is an object", "an object has string property names", and "lets coerce types so that programming is easier". And now it's too late to change. (Although engines of course do optimise unnecessary casting roundtrips away). – Bergi Aug 21 '19 at 22:08