1

I have a global variable in Javascript which is already populated by previous function.

I know I can give this variable nonsense values to test but I think there is another way about it. For instance, I've put some_var = undefined and it works for the purpose of testing typeof some_var == "undefined"

Is there a more professional way of approaching this?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Stivan
  • 1,128
  • 1
  • 15
  • 24
  • you can take any value which does not came from your function as indicator for a deleted value, but `undefined` or `null` may the way to go. – Nina Scholz Mar 23 '16 at 14:11
  • 1
    You *shouldn't* really be deleting variables. A variable should continue to exist as long as it's in scope, only its value should influence anything. Perhaps you should be restructuring your scope to get rid of the variable after you're done with it...? – deceze Mar 23 '16 at 14:14

3 Answers3

3

delete window.some_var; should do the trick.

TN888
  • 7,659
  • 9
  • 48
  • 84
Ran Sasportas
  • 2,256
  • 1
  • 14
  • 21
  • 1
    not if some_var was declared with let or var first. If a variable was once declared with let or var *first* in your script you are stuck with it. Which, btw, is a good thing. – theking2 Jan 28 '20 at 13:11
1

Define your variables like this :

window.some_var = 1;

... or like this :

window["some_var"] = 1;

Then, you can delete them like this :

delete some_var;

... or like this :

delete window.some_var;

... or like this :

delete window["some_var"];

Note :

delete does NOT work if you define your variables like this :

var some_var = 1;
Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169
1

I have a global variable in Javascript which is already populated by previous function

If it is global then

delete window["variable-name"]; //should do the trick

window.x = 1; //equivalent to var x = 1; if x is global
delete window.x;

if you have just the name of the global variable then

window["x"] = 1; //equivalent to var x = 1; if x is global
delete window.x
gurvinder372
  • 66,980
  • 10
  • 72
  • 94