How to cleanly deal with global variables? - javascript

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

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)}

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.

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.

Related

Angular - Should I use local variable or this.variable

I was looking for this but could not find a question as simple as I want it. The problem is really simple: In angular js, should I use local variables, or properties of this (in cases when I don't need to use this).
Example:
// I need "this" here because I need this collection in template
this.collection = SomeService.fetchCollection();
// I can use either "foo" or "this.foo" here, which one is better?
this.fetchSomeData = function(type) {
var foo = AnotherService.foo(type);
return FooService.call(foo);
}
A local variable, so it can be cleaned up as soon as the method exits. Otherwise it would stay unused in the parent's namespace.
But in 99% of cases that will have no real-world effect, so it doesn't matter.
Because you haven't declared 'foo' as a var it will be a global here, which is bad. You should at least prefix it with 'var' so it's scoped to the function and not globally; it shouldn't be available outside the function.
in my opinion it is a good practice not to reveal everything and keep it encapsulated - for example, it avoids moving logic to view which is bad
also, consider that you have a for loop iteration over i variable - would you also use this.i for such purpose?

Are there any repercussions to storing globals like this?

So I know polluting the global namespace referencing the window is a bad thing, especially if you have multiple 3rd party references. So this would be not desirable:
window.someObject = someObject;
That will reference it everywhere. What if I instead use it like this?
var MyApplication = window.MyApplication;
MyApplication.someObject = someObject;
Of course using this approach requires referencing MyApplication = window.MyApplication at the top of each module that needs access to this created namespace. So back to my question. Is this an acceptable approach to giving global access without polluting the window global namespace?
If you want global access, you need to have a global of some sort. This is the common way of doing it.
An example from the jQuery source code:
_jQuery = window.jQuery,
_$ = window.$,
I believe all of the big frameworks do it this way. I'd consider it perfectly acceptable to pollute the global namespace with one container variable.
You can also do (in global context):
(function(lib) {
// in here, lib references window.MyApplication
...
}(MyApplication));
So you can easily change the object passed in.

javascript storing global variables in DOM

I have a fairly large script that contains about 60 global variables. I'm thinking about using the namespace pattern to encapsulate my script and have only one global variable that references one object.
Even though this pattern is considered best practice, I'm also thinking about an alternative: storing the global variables inside the DOM, in hidden divs, and accessing them with $('#MyGlobalVar1').text(). Is this a good idea or not?
Thanks for your suggestions.
No, this is not a good idea.
It pollutes the DOM with non-semantic data, and is less efficient as well. That's even worse than polluting the global JS namespace, and worse still, it only allows you to store strings.
Even if I would recommend you to use a namespace object to hold and reference your data, you can simply put an outer self-invoking function around your code to prevent clobbering the global object.
So you go from
var global1 = true,
global2 = true;
into
(function() {
var global1 = true,
global2 = true;
// rest of all app logic
}());
Beyond that, since you're using jQuery you also might to use jQuerys .data() method. It's designed to reference data for a specific node, but it's internally stored into an ECMAscript object also.

Prevent Duplicate Javascript Variables

So I'm working with WordPress and just spend an hour tracking down an issue between two plugins. They both use the same javascript variable 'd' but for different objects, so I had to change one of them to 'e', but those changes will be lost if the plugin ever updates.
There's thousands of plugins for WordPress, it's no surprise that programmers are using the same variables. Is there a way to prevent your own variables from being accidentally overwritten?
You can wrap your code with a function expression:
(function(){
var e = 1;
}())
In the code above, nothing outside the function can touch your variables and your variables don't destroy other global variables of the same name.
Just remember that since your variables are not visible outside the function, all of your code that refers to them must also be inside it.
The best practice is to use javascript namespaces.
var myApp = {}
myApp.id = 0;

JavaScript: global scope

Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That's working but I want to know what's the best way (good practices) to insert js in my pages and avoid conflicts with scope...
Thank you.
You could wrap them in an anonymous function like:
(function(){ /* */ })();
However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:
var mySingleGlobalObject={};
mySingleGlobalObject.someVariable='a string value';
mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };
or the alternative, shorter syntax (which does the same thing):
var mySingleGlobalObject={
someVariable:'a string value',
someMethod:function(par1, par2){ /* */ }
};
This can then be accessed later from other scripts like:
mySingleGlobalObject.someMethod('jack', 'jill');
A simple idea is to use one object that represents your namespace:
var NameSpace = {
Person : function(name, age) {
}
};
var jim= new NameSpace.Person("Jim", 30);
The best way is to create a new scope and execute your code there.
(function(){
//code here
})();
This is best used when the global scope is accessed at a minimum.
Basically, this defines an anonymous function, gives it a new scope, and calls it.
It's perhaps not the BEST way, but a lot of PHP systems (I'm looking at you, Drupal) take the name of their particular plugin and prepend it to all their function names. You could do something similar, adding the name of your capability to your function names - "mything_do_action()"
Alternately, you could take a more "OO" approach, and create an object that encapsulates your capability, and add all your functions as member functions on IT. That way, there's only one thing in global scope to worry about.

Categories