Deleting var in JavaScript

Posted by fakebenjay on May 28, 2017

I noticed an interesting JavaScript quirk while doing a rudimentary Node.js exercise. In it, you define two global variables, one explicitly and the other implicitly.

global.user = {admin: false}
var account = {balance: 1000}

When you try to delete either one with the “delete” operator, with the syntax “delete VARIABLE”, only ‘user’ goes away, while account survives. Why might this be?

When we say “explicit” and “implicit” here, we’re referring to the nature by which the variable is set. Explicitly set variables are considered properties of the ‘global’ object (which, in browser JavaScript, usually means ‘window’) while implicitly set variables are not, even though they behave very similarly in many contexts.

Despite the severe-sounding name “delete”, the “delete” operator has no direct role in managing or freeing memory, necessarily limiting its role to managing properties of larger objects. As a result, variables declared with ‘var’ can’t be delete from the global scope or a function’s scope, while ‘const’ and ‘let’ variables can’t be deleted from the scope within which they were defined.

If you’re done with a particular variable, the easiest workaround is simply to redefine it as undefined, as follows:

var x = "roses"
y = "thorns"

delete x = false
delete y = true
x = undefined

x //prints undefined
y //ReferenceError: y is not defined