Open In App

How to unset JavaScript variables?

Improve
Improve
Like Article
Like
Save
Share
Report

To know how to unset a variable we must know what are JS variables and how to declare a variable first. JavaScript variables are containers for storing data values. Variables can be declared using the ‘var’ keyword. 

Example : 

var x = 5;

In the above code declaration, the value 5 has been assigned to the variable ‘x’. The unsetting of a variable means to destroy it once its purpose in the code has been fulfilled. 

Here a question arises, do we really need to unset the variables in JavaScript once their job is done? 

The answer is ‘No’. Also, it should be kept in mind that, variables set in the global scope cannot be deleted. It is advised to use var to declare variables in JS, however, the property declared using var keyword cannot be deleted as well. However, if the variable x was defined without using the ‘var’ keyword, then deleting it would have been possible using this method.

Example:

javascript




nxt = undefined;
  
// window is used in JS to access
//  the global variables
window.nxt = 'I am next'
delete window.nxt;


As far as memory management goes, the JavaScript interpreter performs automatic garbage collection for memory management. The job of a garbage collector is to track memory allocation and find when a piece of the allocated memory is no longer needed, in such a case the memory will be freed automatically. The ‘Garbage Collector’ frees the programmer from the worries of the destruction or reallocation of the objects. 

Also, as already mentioned above, the variable cannot be destroyed in JavaScript. So, what could be done now? Some developers may suggest using ‘delete’, but the delete operator removes a property from an object. It cannot remove a variable. So what’s the closest thing that can be done to unset a variable in JS? 

We cannot undeclare a variable. However, we can set its value to undefined for the purpose 

nxt = undefined;  // setting undefined intentionally

Example 1: This example describes delete keywords when var is not used. 

javascript




x = 20;
delete x;
console.log(x);


Output:

  

Explanation: There will be no output in the console, as x gets deleted in this case. However, when var will be used to declare the value of x, the delete function will not work. 

Example 2: The delete doesn’t work when var is used. 

javascript




var x = 20;
delete x;
console.log(x);


Output: 

20

 The console will display the output as 20. ‘var’ has been used to initialize the value of x and thus ‘delete’ function will not work in this case.



Last Updated : 12 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads