Skip to main content

Command Palette

Search for a command to run...

The JavaScript Array Trap: Why Your Missing Values Disappear in Transit

Published
2 min read
The JavaScript Array Trap: Why Your Missing Values Disappear in Transit

I just conquered one of these silent bugs JavaScript introduce into your code. And i must say i feel real good for overcoming this one!

You build an array. You assign values by index. Everything looks fine on the frontend. You send it to the backend and suddenly the array length is wrong.

No errors. No warnings. Just missing data.

Welcome to one of JavaScript’s most subtle foot-guns: sparse arrays.

The innocent-looking code

Imagine you’re collecting answers for an exam:

const answers = [];
answers[5] = "A";
answers[9] = "C";

You might expect answers to represent 10 questions, with only a few answered so far.

And in JavaScript, it sort of does:

answers.length // 10
// But if you log it, you see something like this:
[ <5 empty items>, "A", <3 empty items>, "C" ]

Those “empty items” are not values. They’re holes. And holes change everything.

Where things go wrong: JSON serialization

Most frontends send data as JSON:

JSON.stringify(answers);

JSON does not have a concept of “holes in arrays”. So this:

[ <5 empty items>, "A", <3 empty items>, "C" ]

Becomes this:

["A", "C"]

The number of elements in the array is lost, the index positions for the array is changed.
No way to know those answers were for questions 6 and 10.

From the backend’s point of view, the user only answers question 1 and 2!.

Why is this dangerous?

This bug is nasty because the frontend shows the “correct” length, no exception is thrown, the backend receives valid JSON and data loss happens silently.

If you’re doing grading, scoring, analytics or any positional logic, this can completely break correctness without obvious symptoms. In my case, i was getting wrong markings since i was comparing the submitted result to the expected array.

The right way to model partially-filled arrays

If array length or index position matters, you must make every slot explicit.

The golden rule

Never rely on sparse arrays for data transfer.

What i did to correct the issue:

const answers = Array(totalQuestions).fill(null);
answers[5] = "A";
answers[9] = "C";

Now with this, serialization works as expected, the backend sees correct length and correct index

[null, null, null, null, null, "A", null, null, null, "C"]

JavaScript arrays are not just lists, they’re objects with optional indices. That flexibility is powerful but comes at a cost. If your data is leaving the browser, holes will disappear, length will not be preserved, bugs will be silent. So if position matters, fill your arrays. If position doesn’t matter, don’t use arrays.

Thank you for coming.