To get the last element in an array in TypeScript, you can use array indexing with the length property similar to JavaScript.
In this example,
numbers
with some elements.numbers[numbers.length - 1]
and store it in the variable lastNumber
.lastNumber
to the console.const numbers: number[] = [1, 2, 3, 4, 5];
const lastNumber: number = numbers[numbers.length - 1];
console.log('Last number is:', lastNumber);
Last number is: 5
In this example,
fruits
with some elements.fruits[fruits.length - 1]
and store it in the variable lastFruit
.lastFruit
to the console.const fruits: string[] = ['apple', 'banana', 'cherry'];
const lastFruit: string = fruits[fruits.length - 1];
console.log('Last fruit is:', lastFruit);
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in TypeScript language with well detailed examples.