How to Get the Last Item of a Javascript Array?

javascript

There are different ways to get the last item of a JavaScript array:

  1. Using the length property: You can subtract 1 from the length of the array to get the index of the last item, and then access it with brackets notation.

Example:

var arr = [1, 2, 3, 4];
var lastItem = arr[arr.length - 1]; // 4
  1. Using the pop() method: The pop() method removes the last item from the array and returns it. This can be useful if you need to remove the last item anyway.

Example:

var arr = [1, 2, 3, 4];
var lastItem = arr.pop(); // 4

Note that using the pop() method changes the array itself.

  1. Using the slice() method: The slice() method can be used to create a new array with a subset of the original array. You can use a negative index to start from the end of the array, and set the end index to undefined to include all elements from the starting index to the end of the array.

Example:

var arr = [1, 2, 3, 4];
var lastItem = arr.slice(-1)[0]; // 4

This creates a new array with the last element and then access it with brackets notation.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?