Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
Ghoyos Avatar asked Dec 14 '25 17:12

Ghoyos


2 Answers

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]
like image 149
agm1984 Avatar answered Dec 16 '25 06:12

agm1984


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.

like image 20
Ramzi C. Avatar answered Dec 16 '25 08:12

Ramzi C.