How to cleanly deal with global variables?

As @mplungjan says, best practice is to avoid global variables as much as possible.

Since window is global, you can declare a namespace at any time and within any function by using window.NAMESPACE = {};

Then you can access NAMESPACE globally and set your values on it as properties, from within the same or another function:

NAMESPACE = { var1:"value", var2:"value" /* etc */ };

If you can do all this within script files rather than directly in your page then so much the better, however I guess you may not have the values available in a static script.


It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.

Create a namespace for yourself

https://www.geeksforgeeks.org/javascript-namespace/

More here: https://stackoverflow.com/search?q=namespace+javascript+global

Some examples using different methods of setting the vars

myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}