This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Paul Nikstad
about 12 years

1.4 .length vs position in array

Easy question for any hacker. Could someone explain why an array with four properties has a .length of 4 but the last property number is 3?

I understand that the first property starts at 0 and counts +1 at each array as in: [0”diamonds”, 1”spades”, 2”clubs”, 3”hearts”]

Does javascript count to the 4th position, stop since there are no properties, and return 4?

Will I just have to memorize this as a rule?

Answer 4f663b8f9916fc000301ccbc

3 votes

Permalink

Array indexes start at 0, unlike normal counting where you typically begin at 1. So the 1st item is the 0th, the 2nd item is the 1st, the 3rd item is the 4th, etc… So an array with 4 items would only go to the 3rd index.

points
Submitted by Will Reed
about 12 years

Answer 51a68d5b304609907c0029b6

0 votes

Permalink

I don’t get this. Why does the length equal to 4 and not 3?

points
Submitted by Waseef Akhtar
about 11 years

5 comments

Judy about 11 years

Because there are 4 items in the array.

Waseef Akhtar about 11 years

But the index starts with 0.

Judy about 11 years

Sure, the index does, and the 4 items are indexed as 0, 1, 2, 3.

Waseef Akhtar about 11 years

Oh oh, right on! Thanks a ton. Spare me for my stupidness. I don’t know how could I have not thought about it lol. This is embarrassing.

Judy about 11 years

Not to worry :)