Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to delete?

Tags:

javascript

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?

like image 495
McKayla Avatar asked Apr 14 '11 19:04

McKayla


People also ask

What is the similar meaning of remove?

abolish, clear away, cut out, delete, discard, discharge, dismiss, eliminate, erase, evacuate, expel, extract, get rid of, oust, pull out, raise, separate, ship, take out, transfer.

What is the opposite delete?

Opposite of to remove, get rid of or erase, especially written or printed material, or data on a computer. add. insert. accept. allow.

What is a synonym for changing?

adjustment, advance, development, difference, diversity, innovation, modification, reversal, revision, revolution, shift, switch, transformation, transition, variation, turnaround, adjust, alter, diminish, evolve.


2 Answers

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.

like image 148
Raynos Avatar answered Oct 07 '22 03:10

Raynos


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.

like image 38
Karl Nicoll Avatar answered Oct 07 '22 03:10

Karl Nicoll