McKayla
McKayla

Reputation: 6949

Alternatives to delete?

I've been looking through a lot of blog posts, documentation, etc. about JavaScript's strict mode.

I noticed that there are a lot of restrictions on the delete keyword. I don't even know if you could call them restrictions. It seems like delete just no longer works.

I would love to use strict mode. It's a great idea. But I also think delete is a great idea.

Are there any alternative ways to "delete" a variable?

Upvotes: 11

Views: 8720

Answers (3)

Eli
Eli

Reputation: 17825

As others are alluding to, you should never really need to delete variables. It sounds more like an issue of not properly controlling scope. If you keep your variables in a function scope, they will be deallocated from memory once they are no longer referenced.

Do you have another global namespace other than the global window namespace? It would probably benefit you to have something like that for this situation:

(function(global) {

    var Application = {};

    Application.config = { /* config stuff */ };

    global.Application = Application;

})(window);

// if you need to remove config, you can remove it from
// your object and not the window object:
delete Application.config;

For a real in-depth understanding of deleting and undefined in JS:

http://perfectionkills.com/understanding-delete/

http://scottdowne.wordpress.com/2010/11/28/javascript-typeof-undefined-vs-undefined/

How do I check if an object has a property in JavaScript?

Upvotes: 2

Raynos
Raynos

Reputation: 169401

You do not delete variables.

delete is used to remove a property from an object.

delete foo.a will remove property "a" from object foo.

Why do you need to remove a local variable from scope? You can just set the variable to be undefined

(function(undefined) {
    // undefined is undefined.
})();

(function() {
    var undefined; // undefined is undefined
})();

Another way to check againts undefined would be doing foo === void 0 since void is an operator which runs the expression following it and returns undefined. It's a clever trick.

Upvotes: 6

Karl Nicoll
Karl Nicoll

Reputation: 16419

How about just setting your variables to null? Once you set the variables to null, the JavaScript garbage collector will delete any unreferenced variables on next run.

HTH.

EDIT: As @chris Buckler mentioned in the comments, this can't be done at global scope, as global variables never get garbage collected.

Upvotes: 2

Related Questions