Suppose I have the following code
function myFunction(param, callback) {
...
if (err) {
console.log("error");
console.log(err);
}
else {
callback(data);
}
}
In the case of no error, the callback is called. In the case of an error, it is not. Suppose the calling function looks something like the following
myFunction(param, function(data) {
...
});
Are there memory leak issues or similar? Is there a better way to handle this scenario?
A JavaScript object will not be eligible for reclamation as long as it is strongly-reachable: that is, if it can be reached by traversing the object graph from a root object (which basically amounts to a global property or, possibly closed-over, variable). Any object that is no longer strongly reachable is no longer accessible via JavaScript and will be reclaimed by the GC (when the GC feels like it).
In this case the function-object (callback) passed to
myFunctionis only strongly-reachable for the duration of the function call when it is accessible via thecallbackparameter*. Because the function-object is not strongly-reachable after the function (e.g. it was not saved to a global property) then the function-object is eligible for reclamation – along with any function scopes that it referenced should they no longer be strongly-reachable – as soon as the function terminates.Thus in this case, there is no “memory leak”. However, imagine this case:
Happy coding.
Technically, a real smart JavaScript engine could determine that the object named by
callbackwas no longer strongly-reachable (viacallback) in the “if” branch. I am not sure if any of the JS engines actually go this far, but the question becomes more interesting when talking about function scopes bound in closures (and if this keeps all the objects named by all the variables, even those not accessed later, strongly-reachable).