Jitender
Jitender

Reputation: 7971

How to delete object from window javascript

I need to delete one object in my case. so i am using "delete" keyword but after using it, I am able get the value again

var test= {};
test[0]="111";
test[1]="555";
delete test;
alert(test[0])

Upvotes: 5

Views: 16029

Answers (5)

Alnitak
Alnitak

Reputation: 339816

You can't delete a local variable that has been declared with var.

You can only delete properties of objects - this happens to also include global variables which are implicit properties of the window object.

Upvotes: 7

Andy
Andy

Reputation: 63524

As has been mentioned, you can't delete a variable that has been declared with var.

For example, if you were to change your code to the following - so that test is an explicit property of window - the delete will work.

window.test = [];
window.test[0]="111";
window.test[1]="555";
delete window.test;
alert(window.test[0]);

Upvotes: 6

novalagung
novalagung

Reputation: 11502

you can use test = undefined to make remove object value

Upvotes: 0

Quentin
Quentin

Reputation: 943568

You can delete properties on objects, you can't delete variables.

Either assign undefined or let the variable fall out of scope.

Upvotes: 5

Danilo Valente
Danilo Valente

Reputation: 11342

Whenever delete, it returns a boolean that tells wether it could delete the var or not. In this case, it returns false:

delete test;    // false

You can just set test to undefined:

test = undefined;

Upvotes: 1

Related Questions