Saturday, September 6, 2008

Javascript: Implicit variables are global

Unlike the case in some programming languages, using implicit declaration for a variable in Javascript makes it global. Take a look at the code below:

function foo() {
x = 3;
}

function foo2() {
alert(x);
}

Function foo() *appears* to have a variable 'x' declared within it's scope. Looks can be deceiving, as they say. Unless there is a var declaration, this x is visible globally so if we ran foo() followed by foo2(), foo2() would display an alert dialog with the number 3.

I guess it doesn't really matter much as the code runs within the browser sandbox but you would expect trouble if it were a server-side application and your developers were unaware of this little nuance.

Credits: I have Michael Freidgeim to thank for this bit of info as I read about it from his blog.

No comments: