40

I have a number of aspx pages (50+). I need to declare a number(5-7) of global variables in each of these pages. Variables in one page independent of the other pages even though some might be same.

Currently I am declaring at the page top and outside of any function.

Should I approach this differently and is there any side effects of this approach?

If exact duplicate, please let me know. Thanks

user2864740
  • 60,010
  • 15
  • 145
  • 220
kheya
  • 7,546
  • 20
  • 77
  • 109
  • is it compulsory to use these global variables and no work around at all ? – Ravikiran Feb 21 '11 at 08:56
  • See also [jQuery global variable best practice & options?](http://stackoverflow.com/questions/2866866/jquery-global-variable-best-practice-options) – hippietrail Aug 12 '12 at 08:45
  • Unlike many languages, there's _no_ block and _no_ module namespace in Javascript. Apart from the ones you create explicitly yourself, there are only two namespaces: 1) the function you're inside, and 2) global to _everything_. Javascript variables defined "at the top of a file" and/or "outside any function" are in fact (and with no messages alerting you to that fact) global to _everything_ (not just the block or module). Identical declarations in more than one file will either all refer to the same variable, or "hide" earlier variables. – Chuck Kollars Jun 03 '14 at 02:30

3 Answers3

41

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)}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
3

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.

Dan S
  • 805
  • 5
  • 7
1

One approach would be to declare the variable on "root" level, i.e, outside any code blocks before any other JS code tries to access it.

You can set global variables using window.variablename = value; in order to keep it clean superficially atleast.

Ravikiran
  • 1,440
  • 11
  • 15