Access last element of a TypeScript array

You can access the array elements by it's index. The index for the last element in the array will be the length of the array-1 ( as indexes are zero based).

This should work.

var items: String[] = ["tom", "jeff", "sam"];

alert(items[items.length-1])

Here is a working sample.


If you don't need the array afterwards, you could use

array.pop()

But that removes the element from the array!

The pop returns T | undefined so you need to take care of that in your implementation.

If you are sure there will be always a value you can use non-null assertion operator (!):

     var poped = array.pop()
     array.push(poped!);

Here is another way which has not yet been mentioned:

items.slice(-1)[0]

Here are a the options summarized together, for anyone finding this question late like me.

var myArray = [1,2,3,4,5,6];

// Fastest method, requires the array is in a variable
myArray[myArray.length - 1];

// Also very fast but it will remove the element from the array also, this may or may 
// not matter in your case.
myArray.pop();

// Slowest but very readable and doesn't require a variable
myArray.slice(-1)[0]