- Is Javascript allocating memory for the first 57 "empty" entries in the array?
1. No
JS Arrays may or may not be dense based on the engine, how you construct them, and how you use them afterwards.
Popular engines will create dense arrays whenever you construct them with all its elements defined, and no holes.
Dense array definition:
[0,1,2,3,4];
Array.apply(null, Array(4)); // This is creating an Array expanding the internal Sparse Array as it initial values.
Sparse Array Definition:
[0,,2,3,4];
new Array();
new Array(4);
- If not, how does Javascript keep O(1) for lookups using fragmented memory addresses?
2. Depends on the Array
For dense arrays it will store everything inside the same block of memory.
For sparse arrays it will create a hash table and store pointers to each of the elements independently.
- Is a Javascript Array really an Array or just an Object with integers as keys?
3. They are a type of Object
Arrays are regular Objects, with some properties that let them behave as you would expect.
Accessing elements with integer keys such as 1
(or strings that represent integers such as "1"
) will retrieve whatever is store under that key. Using non-integers (nor string representations of integers) will still set/retrieve Object properties.
Array length
is just an attribute of the Object and its value it's not affected by modifying Object properties.
- What is this design pattern called so that I can research it further?
4. Not sure