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); // 3The element at index 0 gets deleted,
but its slot stays empty - the array's length does not change.
What happens "under the hood"
deleteremoves 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 existWhy this is not recommended
These "empty cells" behave strangely:
-
forEach,map,filterand other methods skip them:javascriptarr.forEach(el => console.log(el)); // prints only 1 and 3 -
But direct access (
arr[1]) returnsundefined.
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); // 2Briefly:
| Method | What it does | Changes length | Creates a "hole"? |
|---|---|---|---|
delete arr[i] | removes a property | No | Yes |
arr.splice(i, 1) | removes an element and shifts | Yes | No |
Conclusion: It is better not to use
delete arr[index]for arrays - it leaves "empty slots" and makes the structure "ragged". Usesplice()for safe removal.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.