How to Unset a JavaScript Variable

To unset a JavaScript variable, you cannot use the delete operator as it just removes a property from an object and cannot remove a variable. Everything depends on how the global variable or property is defined.

If the property is created with let, the delete operator cannot unset it:

Javascript created and the delete operator
let someVar = 1; //create with let, someVar is a variable delete somevar; //return false console.log(someVar); //someVar is still 1

If the property is created without let, the operator can delete it:

Javascript created and the delete operator
someVar = 1; //create without let, someVar is a property delete someVar; //return true console.log(someVar); //error, someVar is not defined

Any property created with var cannot be deleted from the global scope, or the scope of function as well as properties created with let and const also cannot be deleted from the scope they were defined within. They create non-configurable properties that cannot be deleted by the delete operator.

The delete Operator

The delete operator is used to remove a property from an object. If no more references are held to the same property, it is released automatically. The operator returns true for all cases except the one when the property is an own non-configurable property. In such cases false is returned in non-strict mode.