Why can't I remove javascript values ​​declared with var?

Example:

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

I am not interested in how this happens, I want to know why the language has this function.

+6
source share
2 answers

Strictly speaking, the first x not a variable, but a property of a global object. window.x = "Hello" typically have window (therefore x = "Hello" equals window.x = "Hello" ). You cannot use delete to delete variables, but you can use it to delete the properties of an object and what it does in the first case.

+8
source

This page contains a detailed explanation explaining why.

Short answer: delete is for properties, not for variables. var y creates a variable. x = "something" creates a global scope property.

Also note that not all browser handlers delete the same thing. IE cough with cough

+5
source

All Articles