To get the last n elements of an array in JavaScript, you can use the slice() method passing -n as the only argument to slice(). The slice(-n) method will create a new array containing the last 3 elements of the array.
Get The Last n Elements Of An Array In JavaScript
In the following example, we have an array of numbers. We use the slice(-n) method to get the last 3 elements of the array:
const numbers = [-5, 10, 15, 20, 25];
const last3 = numbers.slice(-3);
console.log(last3); // outputs: 15, 20, 25
In the above code, we created an array of numbers and stored it in the variable named numbers. We then called the slice(-n) method on this array, passing -3 as a parameter. This returned a new array containing the last 3 elements of the original array (15, 20, 25).
Similarly, we can get the last 2 elements of the array by passing -2 as the parameter to slice(-n):
const numbers = [-5, 10, 15, 20, 25];
const last2 = numbers.slice(-2);
console.log(last2); // outputs: 20, 25
If you want to get the last element of an array in JavaScript, you can use the slice() method with -1 as the only argument. This will return a new array containing the last element of the original array.
In the following example, we have an array of numbers and we use slice(-1) to get the last element of the array:
const numbers = [-5, 10, 15, 20, 25];
const last = numbers.slice(-1);
console.log(last); // outputs: 25
As you can see, the slice() method is a convenient way to get the last n elements of an array in JavaScript.
slice() method takes two arguments, the first argument is the start index and the second argument is the end index. So, slice(-n) means “from the end to nth elements from the end”.
It is the same as passing slice(arr.length-n) as the first argument.
Here is an example where we get the last 3 elements of an array using slice(arr.length-3):
const numbers = [-5, 10, 15, 20, 25];
const last3 = numbers.slice(numbers.length-3);
console.log(last3); // outputs: 15, 20, 25
In the above code, we use the arr.length-3 to get the starting index of the slice. So, it is the same as passing -3 to slice().