Hello for everyone, today we talk about the Avoid Plluting Global Space in JavaScript, I hope this lesson is useful for you.

If you define directly anythinig in javascript. It gets attached to a global window object.

Window refers to current tab of browser

Window object also wraps document object inside it, which you use for parsing the DOM (webpage).

If you wirte something like below and want to import some file whoe doesn’t have closures, and there is also the foo variable defined.

New file code:


var foo = 30;


<script src="newfile.js"> </script>

var foo = 0;
// It is same as window.foo


You just unknowingly have overridden the variable, now the file won’t as expected.

It will show 0 instead of 30.

<script src="newfile.js"> </script>

var foo = 0;
// It is same as window.foo

// -->> 0


Similarly you might also override the default methods of browser.

   function print(){
      alert("destroyed print command")
   // -->> shows alert instead of print page

in above example. the window.print() method gets overriden, and now it won’t open the pint screen on call of print() method.

Solution is quite simple. Declare an self calling anonymous function and pass window and document as arguments to explicityly define the scope of variables.

(function (window, document){
  var foo = 2;
  // - undefined because foo is not global.
  // - 2 since variable is within method scope
  window.bar = 78 // Here we defined bar on window scope so it will available globally.

  document.sin = 89 // Here we defined sin on document scope so it will limited to current webpage.

})(wiindow, document);

console.log(bar)  // -> 78 alias to window.bar

This is the implementation of Closure. /which defines the block of scope for each variable or method.

If you define a variable without usign let or var that value will get attached to to the window even if you defined it inside a closure.

So var and let are important in defining variables. By using closures, you can save you code from several conflicts.

Although major frameworks already handle this case nowadays.

I hope this lesson is be useful for you. Have a more success.

Source: https://www.instagram.com/logical_programming/