skip to Main Content

My code in javascript

let myArray = ['apples', 'oranges', 'watermelons'];
let index = 3;
let element = myArray[index];
console.log(element);

My output keeps coming up as ‘undefined’ when I try to run the script
How do I display the last element in the array?

2

Answers


  1. Last element’s index is the size of your array minus 1.

    let element = myArray[myArray.length - 1];

    Login or Signup to reply.
  2. let myArray = ['apples', 'oranges', 'watermelons'];
    let index = myArray.length;
    let element = myArray[index-1];

    This will return the last index value of myArray which is 'watermelons'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search