Please consider the following snippet (fiddle here):
var a;
a = 1;
console.log(delete a); // prints 'false'
b = 1;
console.log(delete b); // prints 'true'
Why does the delete
keywords behave differently on the global variables a
and b
?
From the MDN docs:
The delete operator removes a property from an object.
A global variable (without var
) is a property on the global object (typically window
), so can be deleted.
A var
is not a global variable, but a local variable in the outer scope - not a property of the global object - so delete
does not delete it. From those docs:
x = 42; // creates the property x on the global object
var y = 43; // declares a new variable, y
delete x; // returns true (x is a property of the global object and can be deleted)
delete y; // returns false (delete doesn't affect variable names)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With