How to Get Last Items from Array in JavaScript

How to Get Last Items from Array in JavaScript

Ferenc Almasi β€’ 2020 September 13 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

To get n number of last items from an array in JavaScript, simply pass a negative value to Array.slice:

Copied to clipboard! Playground
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

// This will return [9]
console.log(array.slice(-1));

// This will return [8, 9]
console.log(array.slice(-2));
  
// This will return [7, 8, 9]
console.log(array.slice(-3));
array.js

If you only interested in the returned value, you can also unwrap it with pop:

Copied to clipboard!
// This will all return 0
array.slice(-1)[0];
array.slice(-1).pop();
array[array.length - 1];
array.js

In case your array is empty, undefined will be returned.

How to Get Last Items from Array in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.