Dealing with JavaScript Scope

Over at Ajaxian, they've offered up a useful tip for dealing with code that exists in the global namespace and is conflicting with other scripts: move it into its own function. Example:

(function() {

// do you stuff here!


What's the global namespace? That's the window object. Any time you instantiate a global variable, it is automatically part of the window object.

var myvar = 5;
alert(window.myvar); // alerts '5'

For more information on scope, be sure to check out my recent article on Digital Web on that very topic.

Published January 12, 2006 · Updated January 12, 2006
Categorized as JavaScript
Short URL:


1 Comment · RSS feed
Dustin Diaz said on January 12, 2006

That's what object notation is for. You nearly avoid all instances of other global properties.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.