Arr[arr.length -1]

Hello, I just finished the introduction to Arrays lesson and I’m having trouble understanding why this works to get the last element:

const someArray = [1, 2, 3, 4];
console.log(someArray[someArray.length -1]);
//Prints 4

Using square brackets I’m aware that we are printing an element assigned to a specific index. Why does adding -1 after calling the .length property return the final element? I read through all of the MDN documentation on the .length property and didn’t see anything. Isn’t length just used for defining the length of an array and returning the number of elements?


Hello, @thomasbrown11, and welcome to the forums.

In your example above, what is the array length?
What is the index of the last element?
Does the array length minus 1 equal the index of the last element?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.