CodeQL documentation

Deleting non-property

ID: js/deletion-of-non-property
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - language-features
   - external/cwe/cwe-480
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

The delete operator should only be used to delete properties from objects. Using it to delete variables makes code hard to maintain and will break in strict mode.

Recommendation

If the variable you are deleting is a global variable, this is a sign that your code relies too much on global state. Try encapsulating this global state by means of one of the module patterns introduced in JavaScript: The Good Parts.

Example

In the following code snippet, delete is used to clean up the global cache variable used by function get.

var cache;

function init() {
	cache = {};
}

function done() {
	delete cache;
}

function get(k) {
	k = '$' + k;
	if (!cache.hasOwnProperty(k))
		cache[k] = compute(k);
	return cache[k];
}

function compute(k) {
	// compute value for k
	// ...
}

It would be clearer to wrap the whole module into a closure like this (which also avoids exposing function compute to the outside world):

(function(global) {
	var cache;

	global.init = function init() {
		cache = {};
	};

	global.done = function done() {
	};

	global.get = function get(k) {
		k = '$' + k;
		if (!cache.hasOwnProperty(k))
			cache[k] = compute(k);
		return cache[k];
	}

	function compute(k) {
		// compute value for k
		// ...
	}
}(this));

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy