6

example:

x = "Hello";
delete x; // returns true, x is removed

var y = "Hello";
delete y; // returns false, y is not removed

I'm not interested in How this happens, I want to know why the language has this feature.

2 Answers 2

8

Strictly speaking the first x is not a variable but a property of the global object. In browsers it's usually window (so x = "Hello" is equal to window.x = "Hello"). You can't use delete to remove variables but you can use it to remove object properties, and that's what it does in the first case.

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

2 Comments

So can I then see it as, like, removing Properties from objects is like removing Elements from Arrays?
Definitely. delete removes a property from an object. The var keyword attaches your variable to the current local context, while declaring without var implicitly attaches the variable to a global object, i.e window. However, when var attaches to window (root context), delete still won't work.
5

This page has a lengthy explanation that spells out the why.

The short answer is delete is for properties, not variables. var y creates a variable. x = "something" creates a property of the global scope.

Also note that not all browsers handle delete the same. cough cough IE

1 Comment

Nice link :) Just curious, how'd you come across it?

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.