Skip to main content

delete arr[0]

Short answer:

javascript
const arr = [10, 20, 30]; delete arr[0]; console.log(arr); // [ <1 empty item>, 20, 30 ] console.log(arr.length); // 3

The element at index 0 gets deleted, but its slot stays empty - the array's length does not change.

What happens "under the hood"

  • delete removes a property from an object (and an array is an object with numeric keys).
  • It does not shift the remaining elements, and it does not change length.
  • As a result, a "hole" appears in the array - the so-called empty slot.

Demonstration:

javascript
const arr = [1, 2, 3]; delete arr[1]; console.log(arr); // [1, <1 empty item>, 3] console.log(arr.length); // 3 console.log(1 in arr); // false - the element genuinely doesn't exist

These "empty cells" behave strangely:

  • forEach, map, filter and other methods skip them:

    javascript
    arr.forEach(el => console.log(el)); // prints only 1 and 3
  • But direct access (arr[1]) returns undefined.

The correct way to remove an element

Use splice() if you need to shift the remaining elements:

javascript
const arr = [10, 20, 30]; arr.splice(0, 1); console.log(arr); // [20, 30] console.log(arr.length); // 2

Briefly:

MethodWhat it doesChanges lengthCreates a "hole"?
delete arr[i]removes a propertyNoYes
arr.splice(i, 1)removes an element and shiftsYesNo

Conclusion: It is better not to use delete arr[index] for arrays - it leaves "empty slots" and makes the structure "ragged". Use splice() for safe removal.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.