What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?
For example:
myArray = [\
The difference can be seen by logging the length of each array after the delete
operator and splice()
method are applied. For example:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5
The delete
operator removes the element from the array, but the "placeholder" of the element still exists. oak
has been removed but it still takes space in the array. Because of this, the length of the array remains 5.
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4
The splice()
method completely removes the target value and the "placeholder" as well. oak
has been removed as well as the space it used to occupy in the array. The length of the array is now 4.