0
  1. Lets say I create an initial array

let array = [1, "string", false]; //size : 3

  1. Now I add a new element at the index 40

array[40] = "fourty";

The memory for first 3 elements will be contiguous. The assumption is that this element at index 40 will be created at some random memory location. And the elements between index 3 to 38 will not be having any memory allocated.

So the question is how the JS manages to find the item at index 40 without even knowing where to look for ?

  • Depends on the engine. https://stackoverflow.com/questions/1510778/are-javascript-arrays-sparse – epascarello Aug 30 '22 at 17:48
  • "*The memory for first 3 elements will be contiguous*" will it? How can you be certain? – VLAZ Aug 30 '22 at 17:51
  • @VLAZ - Considering that I initialise the array by adding 3 elements, I assume that they shall be contiguous ? Is it not the case ? If so could you explain how it would have been allocated and how JS manages to trace them ? – Kannan Nagasamy Aug 31 '22 at 02:14
  • All of this is implementation dependent. Most certainly if you have mixed types like you've shown and you add something way later, you won't get 37 reserved slots in contiguous memory because it's *impossible* to reserve memory for those. How much memory would you reserve - enough for a boolean? Enough for a number? Enough for a string? Do remember that strings can have basically any size. So, it's literally impossible *and illogical* to create a 41 slot array with slots 3-40 being reserved to be filled later. That only makes sense for homogenous arrays and even then might not be the case – VLAZ Aug 31 '22 at 04:28
  • when they are sparse. Overall the implementation has full control of how an array actually looks like. "JS" doesn't dictate that - Chrome or Firefox may represent it in different ways in memory. Given that arrays should act as objects, it's totally valid to make a sparse or mixed array as an object where each index points to somewhere. Not as contiguous piece of memory. – VLAZ Aug 31 '22 at 04:28

0 Answers0