If I add a value to the 1000th element of a Javascript array, then is there any difference to adding that value to the 0th element assuming those positions are open?
I\'
Due to JavaScript arrays actually being objects, memory is not contiguous. Thus, by your example, accessing array[1000]
without ever storing anything elsewhere will take the same amount of memory as whatever you're storing (not 1000 * size of value).
In fact, doing var arr = new Array(1000);
per Danny's answer does not create an array of 1000 empty slots. It creates an array with a length
property of the value 1000
.
Think about it this way: How is JavaScript to know how much memory to set aside if it doesn't know the type and size of what it's storing?
For example:
var arr = [];
arr[1000] = 'String value';
What's saying I can't come by and store an integer at another index?
arr[0] = 2;
Source: https://stackoverflow.com/a/20323491/2506594