0

I came across this, understood it but still did not know what javascript property it was:

var array = [];

array[1] = true;

array[5] = true;

console.log(array) #=> [true, true]

array[0] #=> undefined

array[1]  #=> true

array[2] #=> undefined

array[5] #=> true

Can someone explain this for me? Thanks

5
  • console.log would have printed [ , true, , , , true ]. Please check again. Commented Jan 13, 2014 at 10:45
  • 1
    Actually it would be [undefined, true, undefined, undefined, undefined, true]. Commented Jan 13, 2014 at 10:46
  • 1
    Or even [1: true, 5: true]. Either way, someone should explain. Commented Jan 13, 2014 at 10:47
  • 1
    Newest chrome prints [undefined × 1, true, undefined × 3, true] :-| Commented Jan 13, 2014 at 10:47
  • 2
    @techfoobar, ugh, that's just nasty. Commented Jan 13, 2014 at 10:47

1 Answer 1

2

Standard arrays in JavaScript aren't really arrays at all, and one effect of that is that they're inherently sparse. That is, an array can have empty slots in it.

That's what you're creating there. After your first three lines, you have an array with two entries in it, at indexes 1 and 5, and a bunch of completely empty slots (indexes 0, 2, 3, 4). Its length property would be 6. When you try to retrieve an element that doesn't exist from an array, you get the value undefined. (This is just a specific case of JavaScript's general behavior: If you try to retrieve an object property that doesn't exist, you get the value undefined.)

The output of console.log with a sparse array will vary depending on what the implementation of console.log does with them. The comments on the question suggest that there are various different ways the console may show the array. You might look at using console.log(array.join()) to get more consistent results. That would give you ,true,,,,true, because it shows blanks for array entries that don't exist (or that contain the value undefined, but in your case, they don't exist).

Sign up to request clarification or add additional context in comments.

1 Comment

Arrays are arrays, but not in Javascript. They may be called Array, but they're really hash objects. The index is just a property, and it has some extra methods that help it pretend to be an array.

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.