Notes of Maks Nemisj

Experiments with JavaScript

Using = null; instead of ;

How often have you done this in you code?

var zork;

Instead of this?

var zork = null;

While it might be used to accomplish the same result, the code above has some hidden pitfall in it. Image situation that you always use the code above, also inside your for statements.

for (code) {
    var zork;
    if (zork) { }
}

If you wouldn’t be careful enough, you might trap in to unwanted situation. Look at the code below:

function tester(makeit) {                                                                                                                                                                                                          
     var length = 5;
     for (var i=0,l=length;i<l;i++){
         var zork;
         if (makeit && 2 == i) {
             zork = 'Defining zork ' + i;
         }
         console.log(i + ':' + zork);
     } 
};
tester(true);

Instead of nulling `zork` variable on every iteration, old value stays untouched, which can bring unexpected situation. Like checking for null value of the `zork` and instead of getting the correct result like:

0:null
VM327:9 1:null
VM327:9 2:Defining zork 2
VM327:9 3:null
VM327:9 4:null

You will get:

0:undefined
VM254:9 1:undefined
VM254:9 2:Defining zork 2
VM254:9 3:Defining zork 2
VM254:9 4:Defining zork 2

Always try to define your variables on top and be explicit, if you want to null it inside loop, then null it.

,

One thought on “Using = null; instead of ;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.