DEV Community

Ship Stack
Ship Stack

Posted on Originally published at youtube.com

Does delete leave a hole in an array in JavaScript?

Deleting an array element looks like it should shrink the array. It does not. Here is what a real run in Node.js 22 printed.

The test

const a = [1, 2, 3];
delete a[1];
console.log(a);                  // [ 1, <1 empty item>, 3 ]
console.log(a.length);           // 3
console.log(JSON.stringify(a));  // [1,null,3]
console.log(1 in a);             // false
Enter fullscreen mode Exit fullscreen mode

Four things fall out of those four lines:

  1. delete removes the property, not the slot. The array keeps its length.
  2. What is left is a hole, not undefined. That is why 1 in a is false.
  3. JSON.stringify turns the hole into null, so the array that goes over the wire has a value where the original had nothing.
  4. Array methods do not agree about holes. forEach skipped index 1 and map kept the hole, while a plain for loop walked every index and Object.keys reported only ["0","2"].

Why it matters

A hole is easy to miss in a log. console.log shows <1 empty item>, but the moment the array goes through JSON.stringify, an API payload or a database column, the hole becomes null and the data quietly changes shape.

const a = [1, 2, 3];
delete a[1];
const round = JSON.parse(JSON.stringify(a));
console.log(round);          // [ 1, null, 3 ]
console.log(1 in round);     // true
Enter fullscreen mode Exit fullscreen mode

After one round trip there is no hole left to detect. Downstream code now has a real null where the original had nothing, and 1 in round flips from false to true.

What to do instead

  • splice(i, 1) when you want to remove an element and shrink the array. [1,2,3] becomes [1,3] with length 2.
  • filter when you want a new array without a value.
  • delete only when you genuinely want a sparse array, which is almost never.
  • If a sparse array might reach JSON.stringify, normalise it first with Array.from(a).

The short version: delete does not remove elements from an array. It leaves a hole, and the hole survives right up until JSON turns it into null.

How this was tested

Every number above came from a real run in Node.js 22. The narration in the video is an AI-generated voice; the output is from the terminal. Short video with the same run: https://youtube.com/shorts/U43-g23Y3mk

Top comments (0)