In many languages, the standard dynamic list (not fixed-size array) type will resize after an item is deleted:
Python:
myList = ['a', 'b', 'c'] del(myList[0]) print(len(myList)) # Prints '2' C#:
var myList = new List<string> {"a", "b", "c"}; myList.RemoveAt(0); Console.WriteLine(myList.Count); // Prints '2' and so on.
However, in Javascript, the list length stays the same, even though the element evaluates to undefined (this tells me that it's different to array[index] = undefined):
Javascript:
var myArray = ['a', 'b', 'c'] delete myArray[0] console.log(myArray.length) // Prints '3' console.log(myArray) // Prints "[ , 'b', 'c' ]" in node, '[undefined × 1, "b", "c"]' in Chrome myArray[0] = undefined console.log(myArray) // Prints "[ undefined, 'b', 'c' ]" on both node and Chrome myArray.splice(0, 1) console.log(myArray) // Prints "['b', 'c']" My questions are:
- Is the JS array
deletebehaviour by design or an oversight that couldn't be fixed for fear of breaking legacy code? - What exactly is the 'undefined-like' value that replaces the deleted array element?
deleteinstruction is not array specific. It's an instruction that you can use on all JS objects to delete a specific property. It meansdeletedoesn't delete an item in an array but deletes the key (array object's property) and turns the array into a sparse one. In JS this is the only way to turn a dense array into a sparse one by removing an item. So it's valuable.