How to handle Global Variable scope issue in JavaScript

Posted on Updated on

One of the major problem with JavaScript is the leakage of scope and which leads to various issues as such variable name conflict. One of the best practice of JavaScript is to use to one global object variable and dynamically add variables to it or defines the variable as object property. This will restrict the variable scope and will help limit scope leakage. This way variables are restricted to one Global Variable scope.

You must be wondering why is this necessary. With new technologies such as AngularJs 1, Angular 2, ReactJs and many other based on JavaScript framework, it has become necessary to understand the concept of Scope and ways it can be controlled.

The controlling of scope leakage by this method is also called Global Abatement.

Declare a variable object in global scope –

We have declared above variable in global scope and on run time wherever required, can add the variable as object property.

or

 

Wherever we require above two variable, it could be used as:

This way we could achieve two things-

1.       Restrict scope leakage

2.       Create mutable object

 

Stay tuned for more update on JavaScript!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.