org.sonar.l10n.javascript.rules.javascript.S3001.html Maven / Gradle / Ivy
Why is this an issue?
The delete
operator is used to remove a property from an object. It only affects its own properties. There are two valid ways to
remove a property:
- Using the dot notation:
delete object.property
- Using the bracket notation:
delete object[property]
delete
will throw a TypeError
in strict mode if the property is a non-configurable property.
delete identifier
may work if identifier
is a configurable property of the global object. For
identifier
to be configurable, it should have been declared directly as a globalThis
property
(globalThis.identifier = 1
). This form is not common practice and should be avoided. Use delete globalThis.identifier
instead if needed.
Aside from that case, deleting variables, including function parameters, never works:
- Variables declared with
var
cannot be deleted from the global or a function’s scope, because while they may be attached to the
global object, they are non-configurable. In CommonJS and ECMAScript modules, top-level variable declarations are scoped to the
module and not attached to the global object.
- Variables declared with
let
or const
are not attached to any object.
var x = 1;
delete x; // Noncompliant: depending on the context, this does nothing or throws TypeError
function foo(){}
delete foo; // Noncompliant: depending on the context, this does nothing or throws TypeError
Avoid using the delete identifier
form. Instead, use one of the valid forms.
var obj = {
x: 1,
foo: function(){
...
}
};
delete obj['x'];
delete obj.foo;
Resources
Documentation
- MDN web docs -
delete
operator
- MDN web docs - Global object
- MDN web docs -
globalThis
- MDN web docs - ECMAScript modules
- Node.js Documentation - CommonJS modules
© 2015 - 2024 Weber Informatics LLC | Privacy Policy