Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Access last element of a TypeScript array

Is there a notation to access the last element of an array in TypeScript? In Ruby I can say: array[-1]. Is there something similar?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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!);
over 4 years ago · Santiago Trujillo Report

0

Here is another way which has not yet been mentioned:

items.slice(-1)[0]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!