Thursday, January 3, 2008

ASP.NET AJAX Best Practices: Use more "var"

Less use of "var" can result into wrong calculation as well as mistake in logic control. And also JavaScript interpreter finds it hard to determine the scope of the variable if var is not used. Consider the following simple JavaScript code:

function pageLoad()
{
i = 10;
loop();
alert(i); // here, i = 100
}

function loop()
{
for(i=0; i<100; ++i)
{
// Some actions
}
}



Here you see, the loop uses the variable i used before in pageLoad. So, it brings a wrong result. Unlike .NET code, in JavaScript variables can go along with the method calls. So, better not confuse the interpreter by using more "var" in your code:



function pageLoad()
{
var i = 10;
loop();
alert(i); // here, i = 10
}

function loop()
{
for(var i=0; i<100; ++i)
{
// Some actions
}
}

No comments: