Reputation: 651
Coming from Java and C ,my understanding of array is that they occupy linear space in memory and hence resizing an array is problematic and only ways to implement resizable arrays is either create one with bigger size and copy all elements or create one with bigger size for future use.
Now, JavaScript arrays are dynamic but I don't understand what happens to the allocated memory when array size is changed, suppose,
const fruits = ["Apple","Orange","Banana"];
Now by my understanding, 3 units of consecutive memory are occupied. Now if I do fruits.push("Kiwi");
, it adds a new element to the array. Now I don't understand how is the memory resized to add the new element. Does JavaScript implement dynamic memory allocation and just links new block of memory to previous one depicting an array?
I read somewhere that JavaScript treats everything as an object. So even if it does treat array as an object, what happens to the underlying memory structure when size changes?
Upvotes: 0
Views: 114
Reputation: 822
Javascript implements dynamic memory allocation as per my knowledge. You keep adding the values inside the array, it will keep allocating the memory as per the values inserted.
Unlike Java static based variables and methods, Javascript works differently.
Upvotes: 1