Categories
TypeScript Answers

How to access the last element of a TypeScript array?

Spread the love

Sometimes, we want to access the last element of a TypeScript array.

In this article, we’ll look at how to access the last element of a TypeScript array.

How to access the last element of a TypeScript array?

To access the last element of a TypeScript array, we can use the length - 1 index.

For instance, we write

const items: String[] = ["tom", "jeff", "sam"];
console.log(items[items.length - 1]);

to define the items string array.

Then we get the last item from the array with index items.length - 1.

Conclusion

To access the last element of a TypeScript array, we can use the length - 1 index.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *