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.

Consider the following array of literals −

const arr = ['a', 'b', 'c', 'd', 'e'];


Let us now execute the following program and guess the expected output −

const arr = ['a', 'b', 'c', 'd', 'e'];
delete arr[4];


The output of this program in the console will be −

[ 'a', 'b', 'c', 'd', <1 empty item> ]

Understanding the output −

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.

Updated on: 10-Dec-2020


Kickstart Your Career

Get certified by completing the course

Get Started