Delete Operator With Var And Non Var Variables
Solution 1:
When a variable is created using a variable declaration (i.e. using var) then it is created with its deleteable flag set to false.
When a variable is created implicitly by assignment without being declared, its deleteable flag is set to true.
It is a peculiarity of the global execution context that variables are also made properties of the global object (this doesn't happen in function or eval code). So when you do:
var a;
Then a is a variable and also a property of the global (window in a browser) object and has its deleteable flag set to false. But:
a = 'foo';
creates a as a global variable without a declaration, so its deleteable flag is set to true.
The result is that you can delete global variables created implicitly, but not those created by declarations (including function declarations).
Solution 2:
Without using var
, assignment with the =
operator is always assigning a property, in your second case the object is implicitly the global object (window
in your browser).
The delete
operator is only for deleting properties on objects, not normal variables.
Solution 3:
The delete operator deletes an object, an object's property, or an element from an array. The operator can also delete variables which are not declared with the var statement.
delete objectName.property
delete objectName[index]
Solution 4:
The delete operator removes a property from an object not the normal variables. Here in this case the object is global implicitly.
On a side note:-
When you write var x = 5
then it declares variable x in current scope ie, in execution context. If declaration appears in a function then local variable is declared and if it's in global scope then global variable is declared.
Whereas when you say x = 5
,then it is merely a property assignment. It first tries to resolve x against scope chain. If it finds x
anywhere in that scope chain then it performs assignment otherwise it creates x
property on a global object.
Post a Comment for "Delete Operator With Var And Non Var Variables"