TIL getting the last element of an array
POSTED ON:
TAGS: arrays javascript
The slice method is very useful in JavaScript when you need to get the last elements of the array. Just pass the negative number as an argument and it will slice the array from the last index.
The Slice method does not mutate your array.
let array = [1, 3, 4, 5, 6, 9, 10, 12]
console.log(array.slice(-1)) // [12]
console.log(array.slice(-2)) // [10, 12]
console.log(array.slice(-4)) // [6, 9 ,10, 12]
Via #2 -
17 Clever JavaScript Tricks That Every Developer Should Use
Related TILs
Tagged: arrays