Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 434
bob Avatar asked Aug 25 '11 11:08

bob


People also ask

What is the benefit of setting a variable to null when you no longer need it?

As soon as you use the variable declare it as null or "" because active variables in js can be read using inspect element. Resetting the variable password to null will keep your password information safe.

Why do we set variable to null?

The set <variable> to null construct sets a project variable to no value. <variable> refers to the variable of bound entity that is referenced in the agent descriptor file.

Is it better to use undefined or null?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

Is null necessary?

You can have an entire programming language without NULL. The problem with NULL is that it is a non-value value, a sentinel, a special case that was lumped in with everything else. Instead, we need an entity that contains information about (1) whether it contains a value and (2) the contained value, if it exists.


1 Answers

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.

like image 105
alex Avatar answered Sep 21 '22 02:09

alex