How to get the last item in an array in JavaScript ?

To get the last item in an array in JavaScript, you can use one of these methods:

1. Using array.length - 1 (Most Common)

Access the last element directly via the array’s length property:

const lastItem = array[array.length - 1];

Example:

const fruits = ["🍎", "🍌", "πŸ₯‘"];
console.log(fruits[fruits.length - 1]); // "πŸ₯‘"

Edge Case Handling:

const emptyArray = [];
console.log(emptyArray[emptyArray.length - 1]); // undefined (no error)

2. Using slice(-1)

Use slice(-1) to get a new array containing the last item, then extract it:

const lastItem = array.slice(-1)[0];

Example:

const numbers = [10, 20, 30];
console.log(numbers.slice(-1)[0]); // 30
console.log(numbers.slice(-2)[0]); // 20 (second-last item)

Note:

  • slice(-1) creates a new array (e.g., [30]), so this is slightly less efficient than direct indexing.

3. Using at(-1) (Modern Browsers)

Use the at() method (ES2022+) to directly access the last item with negative indexing:

const lastItem = array.at(-1);

Example:

const colors = ["red", "green", "blue"];
console.log(colors.at(-1)); // "blue"
console.log(colors.at(-2)); // "green"

Caveat:

  • Not supported in Internet Explorer or older browsers (use a polyfill if needed).

4. Using pop() (Not Recommended)

Use pop() to remove and return the last item (mutates the original array):

const lastItem = array.pop(); // Removes the last item!

Example:

const animals = ["🐢", "🐱", "🐻"];
const last = animals.pop();
console.log(last); // "🐻"
console.log(animals); // ["🐢", "🐱"] (modified array)

Avoid This unless you explicitly want to modify the array.

Comparison Table

MethodProsCons
array[length - 1]Fast, universal, no mutationVerbose syntax
slice(-1)[0]Readable, no mutationCreates a new array
at(-1)Clean syntax, no mutationNot supported in older browsers
pop()Short syntaxMutates the array

Best Practice

Use array[array.length - 1] for broad compatibility, or array.at(-1) in modern environments.

// Recommended approach
const array = [1, 2, 3];
const lastItem = array.at(-1) ?? array[array.length - 1];
console.log(lastItem); // 3

Leave a Reply

Your email address will not be published. Required fields are marked *