find the last element in an array in javascript

To find the last element in an array in JavaScript, you can use the index of the last element, which is equal to the length of the array minus one. Here's some code to demonstrate:

index.tsx
const arr = [1, 2, 3, 4, 5];
const lastElement = arr[arr.length - 1];
console.log(lastElement); // Output: 5
109 chars
4 lines

In this example, we create an array arr with five elements. Then, we use the length of the array to calculate the index of the last element, and store the last element in the variable lastElement. Finally, we log the value of lastElement to the console.

This method works for arrays of any length, even if the array is empty.

related categories

gistlibby LogSnag