Skip to content

Instantly share code, notes, and snippets.

@Yuffster
Created April 11, 2012 21:13
Show Gist options
  • Select an option

  • Save Yuffster/2362647 to your computer and use it in GitHub Desktop.

Select an option

Save Yuffster/2362647 to your computer and use it in GitHub Desktop.
//Foo is in the global namespace. Let's see which closure contents overwrite it.
foo = function() { console.log("FOO"); };
// Defining a named function will never overwrite the global namespace.
(function() {
function foo() { console.log("OH NOES"); }
})();
foo(); //FOO
// Using a multi-line comma delimited list with a var declaration at the
// first item will not overwrite the global namespace.
(function() {
var bar = function() {
console.log("BAR");
},
foo = function() {
console.log("OH NOES");
};
})();
foo(); //FOO
//However, it is simple to create a single typo (semicolon for comma) which will
//cause all following items to overwrite the global namespace.
(function() {
var bar = function() {
console.log("BAR");
};
foo = function() { console.log("OH NOES"); }
})();
foo(); //OH NOES
//Let's reset the global foo before our next example.
function foo() { console.log("FOO"); }
//Here, we see that extraneous commas at the end of a standalone
//global variable declaration do not reliably[1] cause a syntax
//error, and so we will receive no warning that we're unintentionally
//polluting the global namespace.
(function() {
var bar = function() {
console.log("BAR");
};
foo = function() { console.log("OH NOES"); },
bizz = function() { console.log("BIZZ"); }
})();
foo(); //OH NOES
//[1] Internet Explorer will throw a syntax error on extraneous commas.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment