skip to Main Content

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


  1. 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

    let myArray = ['apples', 'oranges', 'watermelons'];
    let index = 2; //correct index is 2
    let element = myArray[index];
    console.log(element);
    
    Login or Signup to reply.
  2. Try this.

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

    Array index start from 0.

    Login or Signup to reply.
  3. Do either of these to get the last element:

    let myArray = ['apples', 'oranges', 'watermelons'];
    
    myArray.at(-1); // newer browsers
    

    or

    myArray [myArray.length - 1];
    

    or

    myArray.pop();
    

    There are a bunch of ways to get the "last" element

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