0

I'm rusty on CS concepts and am watching this review and around 9:00 they talk about arrays being fixed length. This is because they need to tell the stack how much memory to allocate to the structure beforehand so that other memory locations can be allocated elsewhere.

I'm currently a JavaScript developer, but worked with Java in the past. Why is it that a JavaScript array can be dynamically allocated ([].push(element))?

I'm asking this from a more deep level perspective- I understand that Arrays in JS are objects with no concept of "length", but it becomes confusing when you can request the length of an array and access its values by index like an Array.

So does that mean JS objects only interact with Heap memory? Is there any concept of fixed length structures in JS?

user3871
  • 12,432
  • 33
  • 128
  • 268

2 Answers2

3

That aspect of Javascript arrays can be implemented by adding a level of indirection.

Instead of having the array being a contiguous memory area what you can do is having the array being a pointer to a contiguous memory area.

With this approach you still get O(1) element access by index but you can increase the number of elements by moving the elements to another bigger contiguous area.

This is what C++ does with std::vector for example.

Normally these pointer-to-array data structures are also implemented with a "fill pointer". I.e. when you need to increase the size of the array you don't allocate the aread just the needed elements but more, leaving the extra space waiting for more elements to be added in the future.

For example an std::vector in C++ is normally implemented with something like:

struct Vector {
    Element *first;
    Element *beyond_last;
    Element *end_of_storage;
};

where the space between beyond_last and end_of_storage is the memory area ready for the next objects you'll want to push_back into the vector. This way you don't need to re-allocate the whole thing at each and every addition.

6502
  • 112,025
  • 15
  • 165
  • 265
1

Yes, there are fixed length data structures in JS: typed arrays.

var arr = new Uint8Array(50);
console.log(arr.length); // 50
arr[99] = 123;
console.log(arr.length); // still 50
Oriol
  • 274,082
  • 63
  • 437
  • 513