4

I read a book about javascript that said:

var o = {x:1 , y:2 };
delete o ; // Can't delete a declared variable so returns false;

However, the book also states that the variables declared outside any function scope are properties of the global object.

Why aren't we allowed to delete it then if it is a property of the global object?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Anum Malik
  • 554
  • 1
  • 7
  • 11

3 Answers3

3

By saying:

var o = {x:1 , y:2 };

in the top level scope, you are declaring a global variable, which can not be deleted. It does create a property on the global object (which is aliased to the window object in browsers), but it is a special property indeed. However, if you make the declaration like:

o = {x:1 , y:2 };

then you are setting a property on the global scope (remember, the window object) implicitly. The two are similar, but different enough. The delete operator removes an implicit property from an object, but will not delete a variable created on the global object.

Edit, found a more thorough answer

https://stackoverflow.com/a/4862268/1443478

Community
  • 1
  • 1
Brennan
  • 5,632
  • 2
  • 17
  • 24
  • I would specify here that by `o = {x:1 , y:2 };` we are setting _property_ of window **object** (so we can refer to it as `window.o`), which is the same, but sounds more clear in terms of `delete` definition. – Elena Aug 13 '14 at 17:58
1

Since O is already declared and have properties you cannot use delete on the object. You can use

var o = {x:1 , y:2 };
delete o.x ; 

and delete properties here is a DEMO for the same.

V31
  • 7,626
  • 3
  • 26
  • 44
  • `o = {a:true}; delete o; console.log(window.o); //undefined` – 1252748 Aug 13 '14 at 17:44
  • downvote explained by my comment. I can delete it. In my jsbin in the comment to the question, I can see it. maybe i'm wrong. I'll upvote if you can provide a bit more clarity. – 1252748 Aug 13 '14 at 17:47
  • 2
    you never initialized it and is without a var. the question is with a var. hence tried to explain it with it only. – V31 Aug 13 '14 at 17:49
  • I don't understand your last comment. – 1252748 Aug 13 '14 at 17:54
-1

first you have to know what is the work of delete operator.let me explain---

"The delete operator removes a property from an object".here i say it removes an object property not a variable.

in your code you declare a variable.not an object so delete does not work.i think you understand.

o = {x:1 , y:2 }; delete o ;

but the code above is right i think. why? because here o is a property of the global object which is also an object so it work properly.the link which can help you is delete operator

it is my first answer.be happy with coding.

MD. Rejaul Hasan
  • 168
  • 1
  • 15