Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete operator with var and non var variables

Tags:

javascript

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?

like image 340
jforjs Avatar asked Dec 04 '22 07:12

jforjs


1 Answers

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).

like image 56
RobG Avatar answered Dec 06 '22 19:12

RobG