NERDJACKING
Published in

NERDJACKING

Meet “smart array access” technic

A different approach on array access using one of the best ES6 feature

Let’s talk about ⚡️ array access ⚡️.

this is so far one of my favorites tricks on ES6

Work with array is pretty much a standard thing but the access to its items can make some people struggle or create monster code block that can be easily optimized, and remember, readability is gold ⚜️!

The following technic uses ES6 object destructuring, aka smart access, to retrieve values from any position (index) that you want to!

It’s a great choice when you need to access multiple indexes from the same array, and that is the usage key: multiple index.

Benefits

1 — You improve the code optimization and refactoring efforts by centralizing the operation, which mitigates the risks regarding left-overs.

Context

If you use the conventional method to access several values, you need to duplicate the same code block with small changes regarding variable naming and of course, the index you want to access; and one can simply overlook a line and leave a left-over, introducing a small bug that can give a hard time to someone find it.

2 — It uses object destructuring, which any developer familiar with ES6 (ECMAScript 2015) is aware of, with just a small tweak.

3 — And with object destructuring, you can even assign a default value for any item.

Example: const { 0: firstItem = ‘hello world' } = [];

… but how is that possible?

Well, because in the end, arrays are nothing more than object to the javascript interpreter!

Formula

Playground demo

And you, did you know this trick before?

Got something on your mind? Let us know in the comments 💪

--

--

JavaScript and shit done right. Once.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcos Gonçalves

Marcos Gonçalves

Lead Engineer | Architect | Developer Advocate | 12+ years of experience. Also a lover of a good beer in his spare time.