Is it good practice to set variables to null when they are no longer needed?

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.

var fn = function() {

   var local = 0;

   return function() {
      console.log(++local);
   }

}

var returned = fn();

returned(); // 1
returned(); // 2

jsFiddle.

When the inner function is returned, the outer variable’s scope will live on, accessible to the returned inner function.

Leave a Comment

File not found.