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?

1

3 Answers 3

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

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

1 Comment

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.
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.

4 Comments

o = {a:true}; delete o; console.log(window.o); //undefined
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.
you never initialized it and is without a var. the question is with a var. hence tried to explain it with it only.
I don't understand your last comment.
-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.

Comments

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.