DEV Community

Cover image for Avoid using "array[index]" for getting Array elements
Muhammad A Faishal
Muhammad A Faishal

Posted on • Edited on

Avoid using "array[index]" for getting Array elements

Hey there, fellow developers! πŸ‘‹

Let's talk about something that might ring a bell for many of us: accessing elements in an array. We all know that familiar way of grabbing array elements using Property Accessors like array[index]. It's pretty straightforward, right?



const arr = [7]

const firstElement = arr[0]
// 7 βœ…


Enter fullscreen mode Exit fullscreen mode

Problems

Well, here's the catch. Have you ever wondered what happens when you tweak the index? Let's say you change arr[0] to arr[1]. In that case, the value you'd expect from arr[1] suddenly becomes... undefined! 🀯



const arr = [7]

const firstElement = arr[1]
// undefined ❌


Enter fullscreen mode Exit fullscreen mode

Yep, the second element you were counting on just vanishes into thin air. It might sound like a minor hiccup, but guess what? Many developers forget to guard against it!

Now, here's where it gets interesting...

TypeScript, which is a tool that helps catch sneaky bugs, somehow fails to detect this issue. TypeScript still thinks the type of arr[1] is a solid number, despite it being undefined.

First case:
Typescript Example

Second case:

Typescript Example

And you know what's even riskier? When TypeScript considers potentially unsafe data as perfectly safe values, it can trigger nasty errors that are a real headache to debug. 😫

Solutions

But hey, fear not! I've got a couple of solutions that can save the day:

1. Use Array.at()

First case:

Typescript case

Second case:

Typescript case

It's an alternative method to access array elements, apart from the traditional property accessors. By replacing arr[0] with arr.at(0), TypeScript will smartly infer the type as number | undefined.

This method knows how to handle those pesky undefined elements, making your code safer. If you're curious, you can find a polyfill (a code snippet that adds support for new features) for it on GitHub: link to polyfill.

2. Always add fallback

Typescript case

TypeScript will strongly encourage you to add a fallback value whenever you encounter a potentially undefined element. You can go for value = arr.at(0) || fallback.

This way your fallback value will save the day.

Conclusion

By keeping these considerations in mind and implementing these nifty solutions, you'll be dodging bullets and making your code rock-solid. πŸ›‘οΈ So, let's make sure those pesky undefined array elements don't catch us off guard! Hope you find these tips useful for your projects! ✨

Top comments (0)