find the last element in an array in typescript

To find the last element in an array in TypeScript, you can use the square bracket notation to access the last element of the array using the index -1. Here is the code:

index.ts
let arr: number[] = [1, 2, 3, 4, 5];
let lastElement = arr[arr.length-1];
console.log(lastElement); // prints 5
112 chars
4 lines

In this example, we declare an array of numbers, and then access the last element of the array using the index arr.length-1. This works because array indexes in TypeScript (and most programming languages) start at 0, and the last element of the array is always at the index arr.length-1. We then assign this value to the variable lastElement, and print it to the console.

related categories

gistlibby LogSnag