const array = [`a`, `b`, `c`, `d`]; const lastItem = array[array.length - 1];
const array = [`a`, `b`, `c`, `d`]; const lastItem = array.slice(-1);
The neat thing about the above approach is that you don’t need to know the length of the array to grab the last item.
You can also grab the second-to-last item by passing
-2 instead of
slice(), and so on:
const array = [`a`, `b`, `c`, `d`]; const lastItem = array.slice(-2);
However, you must ensure that the number you pass to slice does not exceed the length of the array! Otherwise, an error will be thrown.