Ghoyos
Ghoyos

Reputation: 622

How to log an index of an array in JavaScript?

This question is more of a why does this particular code work this way than a how can I make this code work this way.

Im going through the codecademy tutorials for JavaScript and I came across a lesson that I conceptually can make use of in my own code because I can see the pattern of this particular code - but it doesn't make sense why this code works this way.

Below is an example:

let myArray = ['First','Second','Third'];
var last = myArray[myArray.length - 1];
console.log(last);

The console displays "Third" when running the above code. I know the JavaScript language is a "zero indexed" language and I know that "first" in this array would be position "0" counting from left to right but my question is even if we start at "0" and count every item; 0 then 1 then 2; shouldn't the console log "Second" instead of "Third"? Or does the method of "length" in JavaScript ignore the "0" based indexing system and actually start counting at "1"; in witch case the answer should STILL be "Second" and not "Third"... No matter how my brain adds this up I keep getting "Second" instead of "Third" in my mind even though the output is "third" on the console...

Can anyone explain what I'm missing?

Upvotes: 3

Views: 10484

Answers (3)

P.S.
P.S.

Reputation: 16384

array.length is a number of items in it, there are 3 items. But array indexes starts from 0 and the last index will be 2, not 3. So if you want to get array element using array.length, you need to decrease this length by 1 if you want to get the last element, by 2 if you want to get the previous one and so on.

Upvotes: 2

Ramzi C.
Ramzi C.

Reputation: 1731

Array.length returns the number of items in an array. It has no bearing on the index.

Length - 1 will always be the final index in array though, simply because arrays are 0 indexed in practice.

Upvotes: 2

agm1984
agm1984

Reputation: 17170

Try this code out and it will help. This stuff was tricky for me too. It's just using a variable and calculating it at the same time.

let myArray = ['First','Second','Third'];
var last = myArray[myArray.length - 1];
console.log(last);

First, we have to note that myArray.length is 3 because there are 3 items in it.

Second, now we can re-analyze this but exchange myArray.length with 3:

myArray[3 - 1]

Now, you can see it is simply calculating 3-1, which is 2, so the code is identical to:

myArray[2] // which returns the item at position 2 (starting from 0), [0, 1, 2]

Upvotes: 4

Related Questions