Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKit Howlett
6,774 PointsCan someone please explain Dave's first example used to add to an array?
I understand push() and unshift() but I don't understand Dave's first example of how to add to an array.
numbers[numbers.length] = 7;
I really don't understand what the above does. Can someone please explain by breaking it down?
Thank you!
3 Answers
Steven Parker
231,248 PointsThe "length" of an array is a count of how many items are in it. Since index numbers start at 0, the length value is one higher than the last current index.
So what this code does is to set the item after the current last one, which increases the array size by one.
John Keenan
6,313 PointsAnother good way to look at the original example, when you try calling that array index, it's originally set to an undefined value. You're simply assigning that index a value so that it is no longer undefined.
Shawn Lindsey
20,952 PointsItβs critical to understand here that the length property is returning the absolute number of items in the array, which is 6. The index count of the array itself, however, starts at 0, so it's essentially numbers[5]. But because the length property starts at 1, saying numbers[ numbers.length ] is another way of saying numbers[6]. So by using that length property you've sneakily added 1 to the INDEX because of that starting at 0 versus 1 disparity, and in this example set that new value to 7. I think making this a sequential list of number values in the array created my initial confusion here.