get last element in js in javascript

To get the last element of an array in Javascript, you can use the length property and the index notation to access the last element of the array. Here's an example:

index.tsx
const arr = [1, 2, 3, 4];
const lastElement = arr[arr.length - 1];

console.log(lastElement); // Output: 4
107 chars
5 lines

First, we declare an array arr with some elements. Then we assign the last element of the array to the variable lastElement. To get the last element, we use the length property to determine the size of the array, then we subtract 1 from it to get the index of the last element in the array. Finally, we access the last element of the array using the index notation [arr.length - 1].

Once we've obtained the last element, we can use it as we please in our code.

related categories

gistlibby LogSnag