
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'];
Example
Let us now execute the following program and guess the expected output −
const arr = ['a', 'b', 'c', 'd', 'e']; delete arr[4]; console.log(arr); console.log(arr.length);
Output
The output of this program in the console will be −
[ 'a', 'b', 'c', 'd', <1 empty item> ] 5
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.
Advertisements