JavaScript

How Can I Unset a JavaScript Variable?

In a programming language, the variables are the most important part that acts like a container to store data. Sometimes, for storing new data you have to remove the old data. For that purpose, it is necessary to unset or delete the declared variable from the memory. You can utilize the JavaScript “delete” operator to unset or permanently delete the variable from the memory.

This post will demonstrate the method to delete/unset a JavaScript variable.

How Can I Remove/Unset a JavaScript Variable?

The “delete” operator of JavaScript can be used to exclude/remove a JavaScript variable. Using this allows the user to remove a property of a defined object. However, if you have declared a variable with the help of “var”, “let” and “const” keywords then this operator cannot remove the object. Follow these examples to get a better understanding of the concept:

Example: Unset a Variable
To unset a variable, first, declare a variable as an object and specify its value without using the “var” keyword:

b = 21;

Then, use the “delete” operator with the declared variable to permanently delete it from the memory:

delete b;

Invoke the “console.log()” method and specify the given variable as an argument to show the result on the screen:

console.log(b);

It can be observed that an error message occurred that “b is not defined”:

To avoid such an error, utilize the “window” along with the variable name. The added properties cannot be deleted easily. So, we will add it in a unique way instead of declaring it. To do so, specify the variable value as “undefined”:

variable = undefined;

Utilize the “window” along with the variable name and assign/initialize it with a value:

window.variable = 'Linuxhint';

Now, use the “delete” operator to unset the variable:

delete window.variable;

As a result, it will return the value “true” to show that the variable is deleted from the memory:

That’s all about unsetting a JavaScript variable.

Conclusion

To unset a JavaScript variable, the JavaScript “delete” operator can be used. However, if you have declared the variable by using the “var”, “const” and “let” keywords then, this operator cannot unset the variable. Furthermore, you can delete the variable with the help of a “window” object. This write-up has stated various examples for unsetting the JavaScript variable.

About the author

Hafsa Javed