Today I Learned - Rocky Kev

TIL getting the last element of an array

POSTED ON:

TAGS:

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:

TIL mutations and how to sort without mutating

Mutation isn't bad. It CAN cause side effects and ruin your life. There's times when you want to have your objects mutate. For everything else, switch to functional programming and passing the data.

TIL a clean way to add classes based on the page in Vue

If your pages exist in a array, use the includes() to check.

TIL Finds the differences between arrays

Finds the differences between arrays