Best Way to Get Last Item in an Array

Hello Folks 👋

What’s up, this is SnowBit here. I am a young passionate and self-taught developer and have an intention to become a successful developer.

Today, I am here with a basic topic mostly for beginners and revisers.

Avoid …


This content originally appeared on DEV Community and was authored by SnowBit

Hello Folks 👋

What's up, this is SnowBit here. I am a young passionate and self-taught developer and have an intention to become a successful developer.

Today, I am here with a basic topic mostly for beginners and revisers.

Avoid this

const arr = ["JS", "PY", "CSS"]
const lastItem = arr[2]

Don't do this for getting the last item of an array. Let me explain, this is a small array and contains only 3 items that are easily countable but, what if there are hundred's of items in an array then this method will make you mad 🤯

Do this

const arr = ["JS", "PY", "CSS"]
const lastItem = arr[arr.length - 1]

Here, arr.length becomes dynamic, it increases as you increase items in arr no matter how many you add and that will not make you mad 😜

Thank you for reading, have a nice day!
Your appreciation is my motivation 😊


This content originally appeared on DEV Community and was authored by SnowBit


Print Share Comment Cite Upload Translate Updates
APA

SnowBit | Sciencx (2022-01-20T13:42:13+00:00) Best Way to Get Last Item in an Array. Retrieved from https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/

MLA
" » Best Way to Get Last Item in an Array." SnowBit | Sciencx - Thursday January 20, 2022, https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/
HARVARD
SnowBit | Sciencx Thursday January 20, 2022 » Best Way to Get Last Item in an Array., viewed ,<https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/>
VANCOUVER
SnowBit | Sciencx - » Best Way to Get Last Item in an Array. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/
CHICAGO
" » Best Way to Get Last Item in an Array." SnowBit | Sciencx - Accessed . https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/
IEEE
" » Best Way to Get Last Item in an Array." SnowBit | Sciencx [Online]. Available: https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/. [Accessed: ]
rf:citation
» Best Way to Get Last Item in an Array | SnowBit | Sciencx | https://www.scien.cx/2022/01/20/best-way-to-get-last-item-in-an-array/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.