Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour of delete keyword on global variables

Tags:

javascript

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?

like image 365
Randomblue Avatar asked Sep 14 '12 23:09

Randomblue


1 Answers

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)
like image 165
Eric Avatar answered Sep 20 '22 10:09

Eric