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);
akirtovskis
  • 127
  • 2
  • 2
  • 11

4 Answers4

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);
Saeed
  • 5,413
  • 3
  • 26
  • 40
2

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

Megan D
  • 379
  • 3
  • 13
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.

djfdev
  • 5,747
  • 3
  • 19
  • 38
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);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29