DEV Community

Cover image for Best Way to Get Last Item in an Array
Dhairya Shah
Dhairya Shah

Posted on β€’ Originally published at codewithsnowbit.hashnode.dev

2 2

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

const arr = ["JS", "PY", "CSS"]
const lastItem = arr[2]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 😊

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay