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:

./newfile.js

var foo = 30;

———————————————-

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

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

</script>

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>
<script>

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

window.foo
// -->> 0

</script>

Similarly you might also override the default methods of browser.

<script>
   function print(){
      alert("destroyed print command")
   }
   print()
   // -->> 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;
  console.log(window.foo);
  // - undefined because foo is not global.
  console.log(foo);
  // - 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/