?? The accepted answer (and others) are outdated!
delete
does not remove variables.
(It's only for removing a property from an object.)
The correct way to "unset" is to simply set the variable to null
. (source)
(This enables JavaScript's automatic processes to remove the
variable from memory.)
Example:
x = null;
Use of the delete
operator on a variable is deprecated since 2012, when all browsers implemented (automatic) mark-and-sweep garbage-collection. The process works by automatically determining when objects/variables become "unreachable" (deciding whether or not the code still requires them).
With JavaScript, in all modern browsers:
The delete
operator is only used to remove a property from an object;
it does not remove variables.
Unlike what common belief suggests (perhaps due to other programming languages like
delete
in C++), thedelete
operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. (source)
When using strict mode ('use strict';
, as opposed to regular/"sloppy mode") an attempt to delete a variable will throw an error and is not allowed. Normal variables in JavaScript can't be deleted using the delete
operator (source) (or any other way, as of 2021).
...alas, the only solution:
null
:var x; // ... x = null; // (x can now be garbage collected)
(source)