Know what is sparse array and how to avoid creating it and spending a lot of time debugging it.

I have never heard about sparse array before one of my colleagues shared this interesting issue.
This code looks good to me. What can go wrong!! It should create the array of length = 10 which will have values ranging from 0 - 10.
Let's see....


Whhaaaatttt on the earth is that output.....!!!!
The length of the array is 10 but when we try to access the value at index 0 the output is undefined. Same for other indices.
Ok. That is super weird. Next thing that usually comes to mind is this:
mapisn't working. Let's useforEach.


Nooooooooooo!!

Earlier, at-least we had length 10 which was what we expected. But now we lost that too. As you can see above in the output that length of range is 0 and since length is 0 that's why no element at any indices, that's why we get undefined at range[0]
Code looks correct, then why is it that output is unexpected.
Actually all these unexpected behavior is caused by sparse array.
OK. So what on earth is sparse array ?
Sparse Array
Any
arraywill besparsearray if one of thevalues at any givenindexisempty
Empty value does not mean undefined or null. Empty mean that there is no value at all.
So in above example if I print range in chrome browser console. This will be the output:

Basically new Array(length) will create an array of specified length but all the values will be empty. It's like array has holes in it.
You can create the sparse array by following:

Now we know about sparse array. So let's begin with our initial problem.
So here new Array(10) will create a sparse array of length 10.
Now what will happen when we call map on sparse array ?
As per MDN Docs
Due to the algorithm defined in the specification, if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.
As our whole array is sparse that is why resulting array is also sparse and all the values are blank or empty.
If we have following code, result will be different

As you can see that callback of map does not do anything on the index which is empty.
As per MDN Example
No operation for uninitialized values (sparse arrays)
Which simply means that the callback will not be invoked for empty values.
As our whole new array is sparse, callback will be skipped for all the elements and no value is pushed to range array.
With Array.from

With new Array(length) and fill

Thank you for reading.