I have seen javascript values set to null
at the end of a function.
Is this done to reduce memory usage or just to prevent accidental usage elsewhere?
Is there a good case for doing this. If so when?
var myValue;
.
.
.
myValue = null;
I have seen javascript values set to null
at the end of a function.
Is this done to reduce memory usage or just to prevent accidental usage elsewhere?
Is there a good case for doing this. If so when?
var myValue;
.
.
.
myValue = null;
No it isn't. Every local variable is deleted after the end of a function.
It wouldn't make any difference setting a local variable to
null
at the end of the function because it would be removed from the stack when it returns anyway.However, inside of a closure, the variable will not be deallocated.
jsFiddle.
When the inner function is returned, the outer variable's scope will live on, accessible to the returned inner function.
Yes very much so. Especially if the variable has some secret information such as a returned password.
As soon as you use the variable declare it as null or "" because active variables in js can be read using inspect element.
After evaluating variable password reset it to "". If you do not the value can be accessed by picking any of your existing html items such as a button and using inspect element to add the attribute code
Resetting the variable password to null will keep your password information safe.
There was an issue with iE and circular references involving DOM elements. This was usually created when attaching listeners as follows:
When doStuff ia called, the anonymous function attached to the element has a closure back to the element - a circular reference. In older versions of IE this caused a memory leak so the solution was to set el to null (or anything other than el) to break the circular reference after the assignment to
el.onclick
.The second reason to use it is similar - if a function has a closure that keeps a reference a large object that might otherwise be garbage collected, then it may be useful to remove the reference so that the object can be cleaned up:
So if the function returned to someFunction doesn't actually need to reference reallyBigObject, then the reference can be removed so the closure doesn't keep it from being garbage collected unnecessarily.
Note that you can't prevent the closure to variables in scope, but you can modify their values.
This stuff usually isn't much of an issue unless you are keeping pages open for a long time and doing lots of AJAX and adding and removing lots of DOM nodes. But it's probably a good habit to remove references to objects in closures where they aren't needed.