2008-04-17

JavaScript Reminder - Always Declare Your Variables

Having been developing in Java for some time, the practice of declaring variables (e.g. writing var n = 0; instead of just n = 0; for the first use of the variable n) comes quite naturally. Naturally, that is, except for when initialising a for-loop. Somehow, after getting into trouble with the browser a few times for writing code like for (int i = 0; i < n; i++) out of habit, i gradually fell into writing just for (i = 0; i < n; i++) instead, omitting the int (or var) altogether. After spending quite an amount of time looking at a rather nasty bug earlier, i would just like to remind everyone the importance of the var.

This is a fragment of what i wrote:

function outerFunction()
{
    for (i = 0; someCondition; i++)
    {
        // Do Something
    }
}

function MyObject()
{
    var object = new Object();
    
    object.innerFunction = function()
    {
        // Do Something
        
        for (i = 0; i < n; i++)
        {
            outerFunction();
            
            // Do Something
        }
    };
    
    return object;
}


Upon calling MyObject().innerFunction();, my browser froze, and after a while, came back with a suggestion to terminate the script. Peppering the code with plenty of alerts led to the discovery that the value of i in the inner function's loop would "reset" back to a smaller value after the call to the outer function, and hence never reaching the value of n.

More time spent staring at the code later, i realised that the problem, and hence the solution, was just staring me in the face:

function outerFunction()
{
    for (var i = 0; someCondition; i++)
    {
        // Do Something
    }
}

function MyObject()
{
    var object = new Object();
    
    object.innerFunction = function()
    {
        // Do Something
        
        for (var i = 0; i < n; i++)
        {
            outerFunction();
            
            // Do Something
        }
    };
    
    return object;
}


Remember your vars!

0 comments: