To retrieve the last item of an array in JavaScript, we can use the length property of the array to access the last element. Here's a simple example:
javascriptlet arr = [10, 20, 30, 40, 50];
To retrieve the last item of this array, we can use the following code:
javascriptlet lastItem = arr[arr.length - 1]; console.log(lastItem); // Output: 50
In this example, arr.length returns the length of the array, which is 5. Since array indices start at 0, the index of the last element is arr.length - 1, which is 4. This approach effectively retrieves the last item of the array.
Additionally, if we want this operation to be more flexible and general, we can encapsulate it into a function:
javascriptfunction getLastItem(array) { if (array.length === 0) { return undefined; // If the array is empty, return undefined } return array[array.length - 1]; } console.log(getLastItem(arr)); // Output: 50 console.log(getLastItem([])); // Output: undefined
This function first checks if the array is empty; if it is, it returns undefined, otherwise it returns the last item of the array. This makes the code more robust and better suited for various input scenarios.