I know, that, for example, c++ has something like delete variable and it will be deleted from the memory. Is there something like this in JS.
For example, I have var canSendRequest = true; and after some operations I want to delete it totally from the memory. As I read, delete canSendRequest will not work properly, but I did not manage to find a properly working way. Does someone know, how to do that?
3 Answers
Since JS is garbage collected, you don't have direct control over the release of memory.
You just have to wait for the runtime to free the memory, which it will if there are no permanent references to it via the global object or a permanently existing closure. In those cases, you need to eliminate such references to the variable so that it qualifies to be freed.
If you're saying you want to eliminate the identifier itself from the scope, you definitely can't unless it was a global that was set as a property of the global object, not using proper variable declaration syntax.
Comments
Var is Hoisting type use let or const. like var g_a = 1; //create with var, g_a is a variable delete g_a; //return false console.log(g_a); //g_a is still 1
now try with let and const
1 Comment
let and const are "hoisted" as well, and delete operator is not purposed to delete variables, "g_a is still 1" nevertheless what declaration type you'd use here.In Node.js, their is still no way to clear, control, or modify garbage. Node.js automatically controls memory management and free space.
Note: It only clears those spaces that are no longer used by the program.
In some cases, you may need to modify or clear your memory, and therefore you must modify your codes and restructure them so that you don't need to control or clear your memory. As example, look at this scenario:
In runtime, their is an array declaration like this:
const arr = [2,3,4,5];
Now, in some operation, you need to add 1 at the beginning. Although you can do that by using the Array.unshift method but this will make a reference to your real array, and 1 will be attached forever.
To avoid this kind of garbage collection, you can use the spread (...) operator. Ex:
const newArr = [1,...arr]
myVar = undefineddelete canSendRequestwill work removing the variable from the current context. What do you mean with "will not work properly"?deletedoes in JS. It sort of works with globals under some circumstances, but that's all.