DEV Community

The Holey Array Problem

Abdullah Ali on July 23, 2018

One of the "features" of JavaScript I hate the most is "holey" arrays. If you're unsure what that is, consider the following: const array = [1, ...
Collapse
 
amenadiel profile image
Felipe Figueroa

Why does array[999] = 'HAIL SATAN! ♥' convert the array to a plain object? Is it because of the index or because the special character?

Collapse
 
voodooattack profile image
Abdullah Ali

The index. The content has no bearing on the matter.

When you poke enough holes into the array, V8 deems it as “sparse enough” to get this treatment.

Collapse
 
mohamedlamineallal profile image
Mohamed Lamine Allal

Tank you for the article. Holey make a better allocation against PACKED one (specially matter when the array get big). Against slower operation and access performance. What's the solution to avoid both pitfalls. Is TypedArrays the solution ? Or they have there pitfalls? Typed arrays aren't HOLEY.

Collapse
 
hugoheneault profile image
Hugo Heneault

Great one! One quick question: what are the solutions? :-)

Collapse
 
voodooattack profile image
Abdullah Ali • Edited

The solution is to guard against unbounded inputs when writing to arrays.

You can use if statements to check if the value is within bounds, and throw an error otherwise.

Alternatively, a very simple solution is to use the % modulo operator to constrain the index like this:

array[input % array.length] = value; // will never go out of bounds
Enter fullscreen mode Exit fullscreen mode

With the method above, any out-of-bounds input will be "wrapped around" in the range of 0:N.

For example, if the length of the array is 20 and you supply 10: 10 % 20 = 10, so nothing really changes when the supplied input is within bounds.

But if you supply an out-of-bounds index, say 25: 25 % 20 = 5, and it remains within bounds.

It's worthy to note that this approach also guards against negative inputs, because -25 % 20 equals 15.

Edit: Fixed my numbers. Still waiting on my coffee, sorry.

Collapse
 
yurist38 profile image
Yuri Drabik

Great article! Good to know it, thanks!

Collapse
 
abdulghani200 profile image
Abdul Ghani

Thanks for sharing such a valuable information ❤️