Rule Definition
The delete operator can be used to remove a property from any object. Arrays are objects, so the delete operator can be used here too, but if it is, a hole will be left in the array because the indexes/keys won't be shifted to reflect the deletion. Use the following methods to:
- add/remove elements from the the array : Array.prototype.splice
- add/remove elements from the end of the array : Array.prototype.pop
- add/remove elements from the beginning of the array : Array.prototype.shift
Remediation
Use the following methods to: - add/remove elements from the the array : Array.prototype.splice - add/remove elements from the end of the array : Array.prototype.pop - add/remove elements from the beginning of the array : Array.prototype.shift
Violation Code Sample
var myArray = ['a', 'b', 'c', 'd'];
delete myArray[2]; // Noncompliant. myArray => ['a', 'b', undefined, 'd']
console.log(myArray[2]); // expected value was 'd' but output is undefined
Fixed Code Sample
var myArray = ['a', 'b', 'c', 'd'];
// removes 1 element from index 2
removed = myArray.splice(2, 1); // myArray => ['a', 'b', 'd']
console.log(myArray[2]); // outputs 'd'
Reference
ASCMM-MNT-20
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.