I’m new to Javascript and I try to write a code so it could access to the last element in a given array but it give me "undefined" output as a result. What do I miss here? Thank you all.
// The following code aims to access the element at the last index of an array.
let myArray = ['apples', 'oranges', 'watermelons'];
let index = 3;
let element = myArray[index];
console.log(element);
I followed a tutorial online and come up with this code to access the last element in an array and have no idea why the code does not work.
3
Answers
The first element of an array starts at index 0. So since the array has a size of 3 the last element would have an index of 2
apples – 0
oranges – 1
watermelons – 2
Try this.
Array index start from 0.
Do either of these to get the last element:
or
or
There are a bunch of ways to get the "
last
" element