Sunday, December 6, 2009

Variable Scope with Javascript

Keyword "var" enforces declare a local variable. Otherwise it will be global. Inapproperate use of global variable voilate the idea of OOP, because it has no enforcement of encapsulation. In addition, global variables make code hard to read, maintain, and error prone.


Look at the following code:

function f1()
{
i=10;
fz();
alert(i); // i=100
}
function fz()
{
for(i=0; i++; i<=100)
{
}
}

In function fz, i is considered as global by the compiler/interpreter. To avoid this unexpected result, user "var".

in f1
var i = 10; // tell the compiler this i is a local i (local to the including {})
in f2
for(var i=0 ...)


Another note, even Javascript is a weak-typed language, variable has types too as in other languages. "typeof" operator gets the type of a variable.

typeof x == "string"|"function" |"undefined" ...

No comments: