0

In google chrome console, if I initialize an array:

var arr = [];
arr[5] = 10;

then printing arr in console says:

[undefined × 5, 10]
  1. undefined x 5 is it only chrome's representation or actual memory reserved?
  2. What's the difference between arr[4] and arr[6] as both prints undefined?
  3. What's the use of reserved undefined x 5, if it's actually reserved space?
3
  • 1
    In FF output is little cleaner: Array [ <5 empty slots>, 10 ], so it is different browser representation for the same thing... Commented Sep 18, 2015 at 9:43
  • console.log is browser dependant Commented Sep 18, 2015 at 9:45
  • Similar question Commented Sep 18, 2015 at 9:47

4 Answers 4

2
  1. undefined x 5 is it only chrome's representation or actual memory reserved?

No.

What you are describing is called a sparse array. In Javascript, the arrays are inherently sparse. The existence of arr[5] does not imply the existence of arr[0]. Memory is not allocated up to the max index.

You could see an array in Javascript as a type of Object. The keys are the indices. In fact, you could even do this:

arr[3.14] = 'pi';

3.14 is the key, and pi is the value. A key/value pair. It is similar to declaring this object:

var arr = { '3.14': 'pi' }

The properties that do not exist, well do not exist.

Arrays differ in the way that they are arrays, meaning they have indices and are zero-based. Hence, for indices (read keys) 0 thru to n, the values are undefined.

If you do a arr[200000] = 'something', it does not mean that 0 thru 19999 will be sitting there wasting memory.

  1. What's the difference between arr[4] and arr[6] as both prints undefined?

No difference. Well, "undefined" means undefined. In Javascript you can very well refer to indices well beyond the max declared, and there is no out-of-bound thingy. You only get "undefined".

  1. What's the use of reserved undefined x 5, if it's actually reserved space?

It could be both be a convenience and inconvenient. Just depends on how you see it. Regarding reserved space, no. See point 1 above.

You can easily verify this by iterating the array. See the small example below, and you will understand that 0 thru to 4 do not exist.

Example:

// Only for snippet demo
console.log = function(txt) {  var result = document.getElementById("result"); result.innerHTML += txt + "<br/>"; }
                             
// demo to iterate sparse array
var arr = [];
arr[5] = 10;

arr.forEach(function(elem, idx) {
    console.log(idx + " = " + elem);
});
<p id="result"></p>


There are typed arrays as well. These are not sparse arrays, and hence you cannot introduce gaps with typed arrays. For example:

var int16 = new Int16Array(2);
Sign up to request clarification or add additional context in comments.

7 Comments

This is very technical subject (for amateurs like me), but could i ask why: jsfiddle.net/gcbra0ue array length is 6?
@nevermind: That is because it is an array. Arrays are different form objects in the way that they have indices and are zero-based. Hence, the length of an array would be the highest index + 1. However, the gaps are well, undefined.
Ok, thanks, so memory is not allocated (spaces aren't reserved), there are no 5 variables with default value - undefined, in memory. If i do something like this: var first=arr[0]; then memory space should be reserved (with default value:undefined), if i understand correctly?
Yes @nevermind, now you are explicitly declaring a variable.
@abdul-wahab: (1) arr[4.5] is not enumerable because it is now an Object. However, you can still iterate using the for..in syntax. But, this is now no longer an array. Why? Because arrays are those objects which have a nonnegative integer less than 2^32. (2) As per the official specs of ECMAScript5.1, forEach invokes callback only for elements of the array which actually exist. (3) In any case, remember that JavaScript arrays anyway do not require an up front allocation of memory unlike typed arrays.
|
1

If you assign a value to the x. index of an array that is currently empty, the array length will be updated.

See: Array at MDN, there it says:

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly

4 Comments

If I assign arr[999] = 10 arr.length says 1000. Does it mean, arr reserves 999 undefined elements?
The 'undefined' that comes infront of the message is not relevant to the data in the array. But yes, if you do a console.log for array[0] when data is not provided will result in undefined.
There is no memory reserved as in C arrays, because a JavaScript array is just a list and holds references ("pointers") to its elements.
However, typed arrays are different beasts. They don't allow gap/holes as in untyped sparse ones.
0

Length of array will be 6 in this case as you are allocating 6th position in the array. Rest all the indexes will carry null value..

Example below will give you better idea:

var arr = [];
arr[5] = 10;
document.getElementById('element').innerHTML = JSON.stringify(arr);
<div id='element'></div>

4 Comments

But undefined and null are different primitives. undefined === null results in false and typeof null results in "object".
In this case, JSON can not store undefined, it will store null. The real vale of arr[4] and arr[6] is undefined as you have not defined it anywhere. In any browser this behaviour will not change..
JSON.stringify has nothing to do with sparse arrays. It doesn't know beforehand whether the array you are serialising is having holes or not. It simply iterates using the length and reports null for non-existent properties. The fact is, there are non-existent elements in an array and that's all there is to it.
@Abhitalks, Purpose of using JSON.stringify was to demonstrate length and values present in array nothing more than that..If we define length or an array without really adding values, then the value remains undefined and this is what I want to espress..
-1

it means the sixth entry is 10,

all the other are empty (undefined ).

var arr = [];
arr[5] = 10;
console.log(arr[4])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.