How to get the last N elements from an Array in JavaScript

Javascript get last n elements of array Example; In this tutorial we show you how to get last N elements from an array in JavaScript;

In javascript we can get the last N elements from an array using the slice method, we need to pass -n as a parameter, returns a new array containing the last 3 elements from the original array. let’s see..

Here is an example, that gets the last 2 elements of an array:

const arr = ['h', 'e', 'l', 'l', 'o'];

const last2 = arr.slice(-2); 
console.log(last2);// ['l', 'o']

Similarly, you can get last 3 three elements like this:

const arr = ['h', 'e', 'l', 'l', 'o'];

const last3 = arr.slice(-3);
console.log(last3); // ['l', 'l', 'o']

I hope this example help you.