Hi Friends đź‘‹,

Welcome to Infinitbility ❤️!

Today, we are going to learn How to get the last element of the array in typescript?, here we will use basic array length syntax to find the last element of the array.

So, when we want to know how many elements are in an array we will use array.length and it will return a number of elements in an array.

Well, what we can do here, is we will use array.length minus 1 so we will get the last index of an array.

When we pass the index in an array it will return the last element of an array.

Let’s see what we are going to do…

  1. create sample array list variable
  2. get the last index of the array
  3. get the last element from the array using the index
// create sample array list variable
const domains = ["infinitbility.com", "aguidehub.com", "sortoutcode.com"];

// get last index of array
let lastIndex = domains.length;

// get last element from array
domains[lastIndex - 1];

When you run the above code, you will get sortoutcode.com in your console and which is the last element of the array.

TypeScript, get last element of array example
TypeScript, get last element of array example

All the best đź‘Ť.