EN
JavaScript - array delete operator vs splice method
0 points
In this article, we would like to show you the difference between delete
operator and splice
method on array elements in JavaScript.
The delete
operator will remove the object property, but won't reindex the array or change its length. This makes the element appears as if it was undefined
.
xxxxxxxxxx
1
// index: 0 1 2 3
2
var array = ['a', 'b', 'c', 'd'];
3
4
delete array[0]
5
6
console.log(array); // [ , b, c, d ]
7
console.log(array.length); // 4
8
console.log(array[0]); // undefined
Note:
The value is not in fact set to
undefined
. The property is removed from the array, making it appearundefined
.In the Google Chrome developer tools we can see the following output:
xxxxxxxxxx
1[empty, 'b', 'c', 'd']
or in Node.js:
xxxxxxxxxx
1[ <1 empty item>, 'b', 'c', 'd' ]
The array.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.
xxxxxxxxxx
1
// index: 0 1 2 3
2
var array = ['a', 'b', 'c', 'd'];
3
4
array.splice(0, 1);
5
6
console.log(array); // ['b', 'c', 'd' ]
7
console.log(array.length); // 3
8
console.log(array[0]); // b