The Mystery of JavaScript’s Sparse Array – Why Did Index 0 to 9 Disappear?


While writing the LeetCode #509 Fibonacci Number Solution & Explanation – Zyrastory, I came across the following JavaScript code segment:

var fib = function(n) {
    arr = [0,1];
    for(let i = 2; i<=n; i++)
        arr[i] = arr[i-1]+arr[i-2];
    return arr[n];

⭐ Unlike C# and Java, the length of arrays in JavaScript is not fixed and can be dynamically altered.

This led me to question the behavior of arrays when intentionally skipping indices while assigning values like arr[i] = x. How would the array look like?

Without hesitation, I quickly opened the developer console (F12) and entered the following code snippet:

arr = []
arr[10] = 10

arr.forEach(function(item,index) {
  console.log("index "+index+": "+item);
console.log("Length of arr : "+arr.length)

We can observe that an empty array arr is initially defined, and then index 10 is assigned a value of 10.

Now the question arises, what is the length of the array? Let’s take a guess!

⭐ In this case, the foreach syntax is used, and by the way, let’s also mention some related articles: Unraveling the Peculiar Pitfall in JavaScript – forEach Loop Fails to Exit with return! – Zyrastory

Are you ready? Here’s the answer revealed:


Why is there only one object printed?

But saying the length is 1 is also incorrect, it clearly tells you the total length is 11.

At this point, we have no choice but to check arr[0] ➡ It is undefined.

Now let’s print from index 0 to 9 and see ➡ Not surprisingly, they are all undefined.

And now we come to our topic for today.

Sparse Array

Simply put, a sparse array is when the length of an array does not match the number of its elements.

It’s similar to a row of houses, where a sparse array is like having some houses without any residents inside.

On the other hand, the counterpart we usually use is a dense array, where every index has an element.

How to print it?

In JavaScript, the forEach method only iterates over assigned indices of an array and does not iterate over the unassigned indices in a sparse array.

In this case, you can actually use the most basic form of a for loop.

arr = []
arr[10] = 10

for(let i = 0; i<arr.length;i++)
    console.log("indx"+i+": "+arr[i])
console.log("Length of arr : "+arr.length)
For loop can print the entire array

Now you can see the entire array!


While it may not be immediately clear where sparse arrays can be utilized, it is wise to document and keep them in mind for future needs.

🧡 Hopefully, this post has helped you to some extent.

🧡You can support me by clicking some ad, Thanks a lot

If you got any problem about the explanation, please feel free to let me know

Random post

Leave a Reply

Your email address will not be published. Required fields are marked *