Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How can global variables be avoided in javascript?

user-image
Question added by Rana Alnajjar , Web developer , Lebcards
Date Posted: 2015/07/01
Umair Mehmood
by Umair Mehmood , Sr. Software Engineer , Bindawood Group of Companies

By wrap your code in a closure and manually expose only those variables you need globally to the global scope

Jonathan de Flaugergues
by Jonathan de Flaugergues , software engineer , Abbeal

You have to use IIFE (Immediately Invoked Function Expression).

It's one of best practices development in javascript.

Ernesto Espiritu
by Ernesto Espiritu , Web Developer / Frontend & Backend / Web Designer , mediagraphics

Use namespace like in Java or .Net, they  are very good.... most of the time its more better than totally hiding by pure IIFFE which is closed and later you will be forced to develop API anyways, So practically go the Library way.

 

make1 global variable that will have high chance will be unique in the world, like your website + the uniquename of your library or custom code...

 

var ComYourdomainLibname = (function() { var yourChoice = {prop1 : "prop1",prop2 : "prop2",prop3 : function() {        Console.log( "Do something");        } }return yourChoice;})();

 

In this way, you created1 variable in the global scope with attached methods and properties without polluting the window object, as you wouldn't want attaching function in the window object by just simply using a automatic IIFE () function as it will be pointless, since your still polluting the global/window with function names and variable names, not mentioning object names. but with this method, you will pollute the window object only with1 variable name which is ComYourdomainLibname and you will access your custome methods and properties like ComYourdomainLibname.prop1, ComYourdomainLibname.prop2, ComYourdomainLibname.someMethod() which will be a little typing but saves you future overlapping of libraries.

 

Cheers!

 

P.S. Just check the code quality i type up, probably i missed some construct there, didint run it in an IDE still. for the Pure IIFFE stuff, Its work in special occation when you totally don want anything traceable in your window object, but most of the time... its not helpful for others as the code is just for the program itself, means its closed and you cant do much with it.

George Dimitrov
by George Dimitrov , Unix System Administrator , ADVANCED.IO

In sample words, wrap your code in a closure and manually expose only those variables you need globally to the global scope:

 

(function() {

    // Your code here

 

    // Expose to global

    window['varName'] = varName;

})();

Rehan Farooq
by Rehan Farooq , WEB DEVELOPER/DIGITAL MARKETING EXPERT , Upwork

In JavaScript, objects and functions, are also variables. And any variable declared outside a function has global scope. You probably heard that because JavaScript is a dynamically type language global variables are bad and that they easily become source of confusion and bugs. So how can we avoid of creating any global variable, but still have our code executed?

 

There is such technic, it's called Immediately Invoked Function Expression (IIFE).

 

 

Suppose we have this JavaScript code:

var func = function(){ console.log("entering func"); var counter =0; var innerFunc1 = function(){ counter +=1; console.log("innerFunc1: " + counter); } var innerFunc2 = function(){ counter +=1; console.log("innerFunc2: " + counter); } return { inner1: innerFunc1, inner2: innerFunc2, }; } var f = func(); f.inner1(); f.inner2();

 

So here we have two global variables - func and f.

 

Now I'll show how to run this code without creating ANY global variable by applying IIFE. (function() { var func = function() { console.log("entering func"); var counter =0; var innerFunc1 = function() { counter +=1; console.log("innerFunc1: " + counter); } var innerFunc2 = function() { counter +=1; console.log("innerFunc2: " + counter); } return { inner1: innerFunc1, inner2: innerFunc2, }; } var f = func(); f.inner1(); f.inner2(); }());

 

So actually we wrapped our code inside anonymous function that immediately invokes itself or in other words Immediately Invoked Function Expression (IIFE).

 

The code still executes exactly as it did before but with creating no global variables at all. Happy codding! :)

 

Rahaf Nawash
by Rahaf Nawash , Front End Engineer , Atypon Systems Inc.

Unfortunately global variables can have a bad side effect on the application as it can cause bad interactions with other applications on integration, and this will affect the  resiliency of the code. one technique can be done to avoid this problem is by creating a single global variable for the application that contains all other global variables, for example:

If your application needs the following global variables [x,y,z], you can use a distinguished container name that IS very unlikely to be used in other places like MYAWESOMEAPP and declare you variables like this:

MYAWESOMEAPP.x

MYAWESOMEAPP.y

MYAWESOMEAPP.z

 

Another good way is by the use of modules, as modules work like an interface hiding all its internal implementation.

More Questions Like This