How to handle Global Variable scope issue in JavaScript

How to handle Global Variable scope issue in JavaScript

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 –

var objectDemo = {};

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

objectDemo[propertyDemo1] = “Hello test”;

objectDemo[propertyDemo2] = “Hello World”;


var objectDemo = {

       propertyDemo1: ‘Hello test’,  

       propertyDemo2: ‘Hello World’



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 *