Skip to main content

How to get the last element of an array?

1. Via the index length - 1 (the classic way)

This is the most universal way, and it works everywhere

javascript
const fruits = ["apple", "banana", "cherry"]; const last = fruits[fruits.length - 1]; console.log(last); // "cherry"
  • length is the array's length.
  • Since indexing starts at 0, the last element sits at index length - 1.

2. Via the .at(-1) method (modern, ES2022+)

A nicer and more readable way

javascript
const fruits = ["apple", "banana", "cherry"]; console.log(fruits.at(-1)); // "cherry"

Advantages:

  • You can use negative indexes, like in Python.

  • Works with both arrays and strings:

    javascript
    "hello".at(-1); // "o"

Supported in Node.js 16+ and modern browsers.


3. Using .slice(-1)

javascript
const fruits = ["apple", "banana", "cherry"]; console.log(fruits.slice(-1)); // ["cherry"] console.log(fruits.slice(-1)[0]); // "cherry"
  • slice(-1) returns a new array with the last element.
  • To get the element itself, you need [0].

4. Using destructuring (ES6+)

If you need to pull out the last element elegantly

javascript
const fruits = ["apple", "banana", "cherry"]; const [last] = fruits.slice(-1); console.log(last); // "cherry"

In short:

MethodCodeReturnsNote
Indexarr[arr.length - 1]elementworks everywhere
.at(-1)arr.at(-1)elementmodern
.slice(-1)[0]elementcreates a new array
Destructuringconst [last] = arr.slice(-1)elementelegant, ES6

Conclusion: For cross-browser compatibility, use arr[arr.length - 1]. For modern code, arr.at(-1) looks much cleaner.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.