Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Awkward behaviour of delete operator on arrays in JavaScript
The delete operator in JavaScript is actually an object operator (used with objects).
But since arrays are also indexed objects in JavaScript, we can use the delete operator with arrays as well. However, this leads to some awkward behavior that can confuse developers.
Consider the following array of literals:
const arr = ['a', 'b', 'c', 'd', 'e'];
Example
Let us now execute the following program and observe the unexpected output:
const arr = ['a', 'b', 'c', 'd', 'e']; delete arr[4]; console.log(arr); console.log(arr.length);
Output
[ 'a', 'b', 'c', 'd', <1 empty item> ] 5
Understanding the Awkward Behavior
Since we deleted one index value of the array, we expected the array.length to output 4 instead of 5. But the delete operator only removes the value from the memory location and the location is still occupied by the array.
This makes no change to the length of the array and we still see 5 elements in the array - just one memory location is empty now. The deleted element becomes a "sparse" or "hole" in the array.
Proper Array Element Removal
To properly remove elements from an array, use methods like splice(), pop(), or shift() instead:
const arr1 = ['a', 'b', 'c', 'd', 'e']; arr1.splice(4, 1); // Remove 1 element at index 4 console.log(arr1); console.log(arr1.length); const arr2 = ['a', 'b', 'c', 'd', 'e']; arr2.pop(); // Remove last element console.log(arr2); console.log(arr2.length);
[ 'a', 'b', 'c', 'd' ] 4 [ 'a', 'b', 'c', 'd' ] 4
Comparison
| Method | Changes Length? | Creates Holes? | Recommended for Arrays? |
|---|---|---|---|
delete |
No | Yes | No |
splice() |
Yes | No | Yes |
pop()/shift()
|
Yes | No | Yes |
Conclusion
The delete operator creates sparse arrays with holes, which is rarely desired. Use array methods like splice() for proper element removal that maintains array integrity.
