-2

I have declare global variable in java script, i try to clear with following code but it not clear.

As i defined global variable.

var usno;

then before set value i tried following code

delete window.usno;
usno = undefined;
usno=null;

but no success.

Please help on this

Thanks Basit.

user3069097
  • 59
  • 1
  • 12
  • "No success" at what? What are you trying to do? What did you expect to happen? – JJJ Jul 18 '15 at 18:59

2 Answers2

1

In short, you cannot delete variables defined with var. If you set the variable using window.usno then it can be. See Understanding delete and the answers to How to unset a JavaScript variable? for more details.

Do you really need to delete the variable though? Instead of making a global variable, restrict the scope of your variable to a function so that it will be garbage collected after the scope of the function ends.

Community
  • 1
  • 1
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
  • I don't know whether i want to delete or not. for what purpose im using is when user login the saved value in usno. suppose when i run the login screen when user "A" is login i save A value in usno and when user "B" login then i save B value in usno. but what problem is taking always "A" value – user3069097 Jul 18 '15 at 19:34
0

Your first solution is the correct one.

delete window.usno;

That deletes the property usno from the global window object. But here is where the confusion lies, when we test it:

window.usno; // -> undefined

So, a deleted or non-existent property returns undefined. Thus, in effect, the following two statements achieve much the same thing:

delete window.usno;
window.usno = undefined;

They are not exactly the same thing. In the second case, the usno property still exists, as you will find if your iterated through all of the properties of window.

Short answer:

delete window.usno;
kieranpotts
  • 1,510
  • 11
  • 8