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:
var
outside a function) are properties of the "global object", which in web browsers iswindow
. So -var a = 1; delete window.a; console.log(a);
will successfully delete the variable and cause the last line to issue a reference error. – Tribble