Friday, September 5, 2008

Variable scope in Javascript

I'm from an old skool of JavaScript where it was a nice add-on and everything was done on the server. Sure, i've used all the JQuery, Ajaxy, Prototypey frameworks out there but i never went back to look at the core of the language - well at the moment i'm working on something and writing a lot of script.

So i learned something new. A lot of frameworks were using the following syntax in their libraries..

(function() {


It's fair to say i was going mad trying to figure out why. I mean you put an alert in there and it pops up when the script loads. So why bother with the function? Why not just write your code as we used to - directly in the page?

Well, thanks to this paper, I have discovered why and this note is as much for my future reading as yours :)

Turns out that you can locally scope variables within these anonymous javascript functions which more importantly means you don't screw up global vars that are being used elsewhere. So you can confidently write the following ...
var person = 'steven';
(function() {

var person = 'xavier';

alert("Person 1 " + person);


alert("Person 2 " + person);

... and you will get "Person 1 xavier" and "Person 2 steven" - notably the global variable "person" was redeclared within the scope of the anonymous function and the name changed, but as it was declared with "var" it does not overwrite the global value. If you did NOT use "var" in the function, you would change the value globally. So it works like every other programming language - just a wee bit different in term of syntax :)

No comments: