gemma cass
gemma cass

Reputation: 61

How does this arrays length equal 10?

Sorry if this is a stupid question, I'm new to programming and I just don't get this.

I know an array is 0 indexed, but I still don't understand how this code gives me 10.

var array = [];
array[3] = "Hello";
array[9] = "Goodbye";

console.log(array.length);

Upvotes: 1

Views: 205

Answers (2)

user11269493
user11269493

Reputation:

var array = [];
array[3] = "Hello";
array[9] = "Goodbye";

console.log(array.length);

Now, you have var array = [undefined, undefined, undefined, "Hello", undefined, undefined, undefined, undefined, undefined, "Goodbye"] which means there are now 10 values in your array (most of them being undefined since you skipped indexes).

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371079

See MDN:

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

For this situation, the first sentence is a bit misleading, but the second isn't. The largest array-index property that the array object has is 9, so the .length of it is 10 (9 + 1).

What you have there is a sparse array, but sparse arrays are very odd and have numerous unintuitive behaviors (like this one) - they should probably be avoided in almost all cases. To avoid having a sparse array, when assigning to a particular index of an array, make sure that every array index below it also has been assigned a value. (Eg, don't assign to [2] unless [1] and [0] have also had values assigned to them)

If you want to associate arbitrary numbers with data, but using an array would result in it possibly being sparse, then use an object instead, eg

const wordsByNumber = {
  3: 'Hello',
  9: 'Goodbye'
};

Upvotes: 9

Related Questions