0

I used delete keyword to delete a variable but it doesn't seem to work....

var txt = "Some text";
alert(txt); //Output - Some text
delete txt;
alert(txt); //SAME OUTPUT - Some text

1 Answer 1

1

delete is used to delete properties, not variables. That is, it is used to remove a property from an object.

According to MDN's explanation of delete, "You can use the delete operator to delete variables declared implicitly but not those declared with the var or the function statement."

So the behaviour you've described is correct.

Sign up to request clarification or add additional context in comments.

5 Comments

To delete a variable, you have to do txt = undefeind.
@Derek: That doesn't delete a variable, it simply assigns it the "value" undefined. It does, however, allow what the variable previously referenced to be garbage collected unless there are other references to it (in other variables). There is a difference between a variable or property that doesn't exist and a variable or property that exists but has the "value" undefined.
So that's mean you can't really delete a variable? Once you declared a variable and that's it, it will not be able to be deleted?
You don't really need to delete variables: setting them to undefined will let the browser free up the memory because the thing the variable referenced can disappear - but it's like emptying a box: the box itself doesn't vanish into thin air.
delete window.txt works if you created it with window.txt = ... in the first place, but not if created with var. And of course window only applies to global variables. It's good practice for unrelated reasons to avoid (too many) globals, so if you use a namespacing scheme your "variables" would actually be properties of your namespace object so you cold delete them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.