0

I am trying to access the last value of an array, but don't understand why this doesn't work.

const arr = [2 , 3, 6, 8];
const end = arr[ arr.length ];
console.log(end);

But when I try console logging the value it returns 4, which is what I was looking for with previous code :

console.log(arr.length);
3
  • Arrays are zero indexed, so the indexes are 0, 1, 2, 3 if you want the last element it's arr[arr.length -1] Commented May 4, 2018 at 18:10
  • Arrays are zero indexed so you might want to think about what that means for the arr.length.. Commented May 4, 2018 at 18:10
  • last array of element is at index length -1 Commented May 4, 2018 at 18:10

4 Answers 4

6

Arrays are zero-based indexing. Which means The first element of the array is indexed by subscript of 0 and last element will be length - 1

const arr = [2 , 3, 6, 8];
const end = arr[ arr.length - 1 ];
console.log(end);

Sign up to request clarification or add additional context in comments.

Comments

3

JavaScript array indexes start counting at 0. So...

arr[0] evaluates to 2

arr[1] evaluates to 3

arr[2] evaluates to 6

arr[3] evaluates to 8

arr.length evaluates to 4 because there are 4 elements in your array

arr[4] refers to the 5th element in an array, which in your example, is undefined

Comments

0

Arrays are 0-indexed. The last item of the array can be accessed with arr[arr.length - 1]. In your example, you're attempting to access an element at an index that doesn't exist.

Comments

0

Array index always start with 0 and Array length is equal to counts of element in array

value   => [2,3,6,8]
indexes => [0,1,2,3]

that is why arr[4] coming undefined because there is not value at index 4.

const arr = [2 , 3, 6, 8];
const end = arr[ arr.length-1 ];
console.log(end);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.