I tried delete a variable in javascript using delete operator, but found some issue. Can you guys please explain the below code, and why it is happening
>> var a = 5;
>> delete a
false
>>a
5
>> b=5;
>>delete b
true
>>b
ReferenceError b is not defined
why var a = 5 and b = 5 are different?
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).
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