Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I delete javascript values declared with var?

Tags:

javascript

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.

like image 524
NomenNescio Avatar asked Apr 13 '13 11:04

NomenNescio


2 Answers

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.

like image 61
JJJ Avatar answered Oct 13 '22 04:10

JJJ


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

like image 28
Steve Kallestad Avatar answered Oct 13 '22 04:10

Steve Kallestad