I have a global variable in JavaScript (actually a window
property, but I don't think it matters) which was already populated by a previous script but I don't want another script that will run later to see its value or that it was even defined.
I've put some_var = undefined
and it works for the purpose of testing typeof some_var == "undefined"
but I really do not think it's the right way to go about it.
What do you think?
This question is related to
javascript
global-variables
undefined
variable-declaration
unset
TLDR: simple defined variables (without var
, let
, const
) could be deleted with delete
. If you use var
, let
, const
- they could not be deleted neither with delete
nor with Reflect.deleteProperty
.
Chrome 55:
simpleVar = "1";
"1"
delete simpleVar;
true
simpleVar;
VM439:1 Uncaught ReferenceError: simpleVar is not defined
at <anonymous>:1:1
(anonymous) @ VM439:1
var varVar = "1";
undefined
delete varVar;
false
varVar;
"1"
let letVar = "1";
undefined
delete letVar;
true
letVar;
"1"
const constVar="1";
undefined
delete constVar;
true
constVar;
"1"
Reflect.deleteProperty (window, "constVar");
true
constVar;
"1"
Reflect.deleteProperty (window, "varVar");
false
varVar;
"1"
Reflect.deleteProperty (window, "letVar");
true
letVar;
"1"
FF Nightly 53.0a1 shows same behaviour.
You cannot delete a variable if you declared it (with var x;
) at the time of first use.
However, if your variable x
first appeared in the script without a declaration, then you can use the delete
operator (delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.
Note that delete
returns true
when it was successful.
Update 2021: tested on Chrome 88 and Firefox 84:
implicit_global = 1;
delete implicit_global; // true
window.explicit_global = 1;
delete explicit_global; // true
const _object = {property: 1};
delete _object.property; // true
function_set = function() {};
delete function_set; // true
function function_declaration() {};
delete function_declaration; // false
(function () {
var _var = 1;
console.log(delete _var); // false
console.log(_var); // 1
})()
(function () {
let _let = 1;
console.log(delete _let); // false
console.log(_let); // 1
})()
(function () {
const _const = 1;
console.log(delete _const); // false
console.log(_const); // 1
})()
Original answer is no longer relevant. tested in 2015 on Chrome 52:
implicit_global = 1;
window.explicit_global = 1;
function_set = function() {};
function function_dec() { };
var declared_variable = 1;
delete implicit_global; // true, tested on Chrome 52
delete window.explicit_global; // true, tested on Chrome 52
delete function_set; // true, tested on Chrome 52
delete function_dec; // true, tested on Chrome 52
delete declared_variable; // true, tested on Chrome 52
Edited updated to clarify the various options (depending on what your desired intentions are)
See @noah's answer for full details
//Option A.) set to null
some_var = null;
//Option B.) set to undefined
some_var = undefined;
//Option C.) remove/delete the variable reference
delete obj.some_var
//if your variable was defined as a global, you'll need to
//qualify the reference with 'window'
delete window.some_var;
References:
MDN SyntaxError when deleting an unqualified variable name in strict mode
?? 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)
Variables, in contrast with simple properties, have attribute [[Configurable]], meaning impossibility to remove a variable via the delete operator. However there is one execution context on which this rule does not affect. It is the eval context: there [[Configurable]] attribute is not set for variables.
I am bit confused. If all you are wanting is for a variables value to not pass to another script then there is no need to delete the variable from the scope. Simply nullify the variable then explicit check if it is or is not null. Why go through the trouble of deleting the variable from scope? What purpose does this server that nullifying can not?
foo = null;
if(foo === null) or if(foo !== null)
@scunlife's answer will work, but technically it ought to be
delete window.some_var;
delete is supposed to be a no-op when the target isn't an object property. e.g.,
(function() {
var foo = 123;
delete foo; // wont do anything, foo is still 123
var bar = { foo: 123 };
delete bar.foo; // foo is gone
}());
But since global variables are actually members of the window object, it works.
When prototype chains are involved, using delete gets more complex because it only removes the property from the target object, and not the prototype. e.g.,
function Foo() {}
Foo.prototype = { bar: 123 };
var foo = new Foo();
// foo.bar is 123
foo.bar = 456;
// foo.bar is now 456
delete foo.bar;
// foo.bar is 123 again.
So be careful.
EDIT: My answer is somewhat inaccurate (see "Misconceptions" at the end). The link explains all the gory details, but the summary is that there can be big differences between browsers and depending on the object you are deleting from. delete object.someProp
should generally be safe as long as object !== window
. I still wouldn't use it to delete variables declared with var
although you can under the right circumstances.
If you are implicitly declaring the variable without var
, the proper way would be to use delete foo
.
However after you delete it, if you try to use this in an operation such as addition a ReferenceError
will be thrown because you can't add a string to an undeclared, undefined identifier. Example:
x = 5;
delete x
alert('foo' + x )
// ReferenceError: x is not defined
It may be safer in some situations to assign it to false, null, or undefined so it's declared and won't throw this type of error.
foo = false
Note that in ECMAScript null
, false
, undefined
, 0
, NaN
, or ''
would all evaluate to false
. Just make sure you dont use the !==
operator but instead !=
when type checking for booleans and you don't want identity checking (so null
would == false
and false == undefined
).
Also note that delete
doesn't "delete" references but just properties directly on the object, e.g.:
bah = {}, foo = {}; bah.ref = foo;
delete bah.ref;
alert( [bah.ref, foo ] )
// ,[object Object] (it deleted the property but not the reference to the other object)
If you have declared a variable with var
you can't delete it:
(function() {
var x = 5;
alert(delete x)
// false
})();
In Rhino:
js> var x
js> delete x
false
Nor can you delete some predefined properties like Math.PI
:
js> delete Math.PI
false
There are some odd exceptions to delete
as with any language, if you care enough you should read:
The delete operator removes a property from an object.
delete object.property
delete object['property']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
According to the question you need one of followings
delete some_var;
delete window.some_var;
delete window['some_var'];
ECMAScript 2015 offers Reflect API. It is possible to delete object property with Reflect.deleteProperty():
Reflect.deleteProperty(myObject, 'myProp');
// it is equivalent to:
delete myObject.myProp;
delete myObject['myProp'];
To delete property of global window
object:
Reflect.deleteProperty(window, 'some_var');
In some cases properties cannot be deleted (when the property is not configurable) and then this function returns false
(as well as delete operator). In other cases returns true
:
Object.defineProperty(window, 'some_var', {
configurable: false,
writable: true,
enumerable: true,
value: 'some_val'
});
var frozen = Object.freeze({ myProperty: 'myValue' });
var regular = { myProperty: 'myValue' };
var blank = {};
console.log(Reflect.deleteProperty(window, 'some_var')); // false
console.log(window.some_var); // some_var
console.log(Reflect.deleteProperty(frozen, 'myProperty')); // false
console.log(frozen.myProperty); // myValue
console.log(Reflect.deleteProperty(regular, 'myProperty')); // true
console.log(regular.myProperty); // undefined
console.log(Reflect.deleteProperty(blank, 'notExistingProperty')); // true
console.log(blank.notExistingProperty); // undefined
There is a difference between deleteProperty
function and delete
operator when run in strict mode:
'use strict'
var frozen = Object.freeze({ myProperty: 'myValue' });
Reflect.deleteProperty(frozen, 'myProperty'); // false
delete frozen.myProperty;
// TypeError: property "myProperty" is non-configurable and can't be deleted
Source: Stackoverflow.com