Global variables in JS harmful? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
According to this article
http://www.mediaevent.de/javascript/globale-lokale-variablen.html
Global variables are in JS pretty dangerous.
I'm sorry that it's in German, but I'm gonna point out out the 2 main statements of the article.
The first is already in the 2nd paragraph of the head statement.
It says something like "In JS global var's are dangerous as they can get accessed by other scripts over the name" That's fine so far, as that's mostly the way why I want to use global var's don't I?
But in the article it sounds as this could happen randomly. and that's for sure not the expected behaving, is it?
But what is much more frightening me is the second last sentence. It forecasts that memory leaks will generated if a function that declares a
global variable is called multiple times.
But how could this happen if the name is still the same? how there can be multiple vars declared global with the same name?
Or is this article probably written by some one just "half-knowledge"? Or maybe just addressed to some one who isn't used to the difference between global and local at all?
Or is JS really behaving in this way?
Now a concrete example:
I want some one who logs in to my page to create a Random generated token and submit it by clicking login.
on each other button I want that this token is accessed by a different function and just submit it, so that just for a new login the key will be regenerated.
For that key I was thinking about using a global variable, which gets declared by one function and gets returned by another.
But as I will generate/regenerate the key possibly more then once, would this generate memory leaks? Or is this article I'm referring to probably just dramatizing?
If this is really the way JS is behaving, what would be a good way to make a variable accessable from different functions in my case?

The problem with globals is not memory, and it's not performance.
The problems with globals is entirely different. The problems are that they introduce global state and that scripts are not bound to a namespace.
Let's go through these problems one by one.
Having global state
This is the biggest issue here. Coding necessitates that the dependencies of a module be explicit and that communication between pieces of code is very clear.
When you have global variables which part of the code uses the variable is not nearly as clear and you can't be sure what part of the code needs it and what does not.
Let's say I have a Zoo project and I have a Bathe service that cleans an animal. Instead of passing Bathe around to each animal that needs it I have it on a global namespace and I just call Bathe(myAnimal).
Now I want to restructure my zoo and I want to know which animals need bathing because I want to optimize that. I have no way of knowing that other than going through my whole code. In order to see if my Giraffe needs bathing I have to read the entire code of the Giraffe class. If instead I passed Bathe to the constructor of Giraffe instead of using it or creating it inside giraffe (a concept called dependency injection) I can see that a Giraffe needs bathing just by reading the signature.
Now this can get way worse, what if I have state? If I'm actually changing a global variable in multiple places it becomes extremely hard to track. In a more than a few lines code base this means that you have state changing all around and no clear indication of who is changing it.
This is the main reason you should avoid globals altogether .
Scripts are not bound to a namespace
If I have two scripts on a page and my first script declares a A variable on the global namespace, the second script can access that variable. This is useful because scripts can interact this way but it's very harmful because it means that scripts can override each other's code, and communicate in an unclear way.
This of course is completely mitigated if you use a module loader like browserify or RequireJS which means your whole script only exposes two globals - require and define and then script loading is done through the loader.
This way the way independent pieces of code interact is well defined. That doesn't prevent you from creating variables on the global object, but it helps mitigating the need to do so in a uniform manner.
A note on security
Of course, anything on the client side is compromised, you can't do security or anything like that in client side JavaScript on an insecure browser (that is, you didn't prevent anything external on) because the client can just run arbitrary code on your code and read it.

There are three big problems with global variables:
name collisions
code complexity
garbage collection
Name collision
The problem with having variables in global scope is that you have less control over what else is in that scope. Your code uses a ga_ variable globally and works fine, but when you add a Google Analytics snippet that uses the same variable things unexpectedly fail and it can be quite hard to see why your shopping cart fails 2 out of 3 page loads.
If you can wrap your code in an IIFE to prevent having any variables in global scope, you should do that. Obviously there are cases where you actually want to have your code accessible globally (ex: jQuery library). In those cases, it is best practice to keep all your stuff in a single namespace (jQuery) with a relevant name.
Code complexity
It is usually a good idea to partition your code so that individual pieces have minimal interactions with each other. The more pieces interact the harder it is to make changes and to track down where bugs come from. Obviously a global variable can be accessed anywhere so when you have a problem with some code that accesses a global variable, you have to inspect every usage of that variable which can be quite a big pain. The thing to do to avoid these pains is to keep variables as local as they can be and encapsulate pieces of code so they can't interact with each other except through specific interfaces.
Memory leaks
In JavaScript you have little control over the garbage collection process. All that is guaranteed is that if you can access a variable it will not be garbage collected. This means that if you want something to be garbage collected, then you must make sure you can't access it anymore. While a global i variable which keeps a number won't be a big deal, as #Boluc Papuaccoglu mentioned when your global variable keeps more and more properties over time (an array of XHR requests for example, or array of created DOM objects), the memory consumption turn into a big deal.
All of these situations are worst case scenarios and you probably won't have issues with a small application. These recomendations have most value when you're starting to learn programming because they develop good habits and when you're working on complex applications when they save you time and money wasted on debug or difficult to do improvements.

Regarding memory leaks: Let's say you have a function, and within it you define a var, and use it for some purpose then return from the function. In this case, the memory used by the variable will be freed. However, if you relied on a global variable to do the same thing, then the memory would continue to be allocated long after your function exited. Extending the same scenario, imagine that your function adds properties to this variable with names that depend on the data the function is processing (like Order ID, Customer Name, etc.) Now, each time your function gets called, more and more properties will be appended to this variable and it will grow and grow.

Related

How do I create a global variable in Qualtrics Question Text?

How do I create a variable to use in my text using a Qualtrics survey in multiple questions? I am not using any embedded data or making variations. The variable would be for the sole purpose of editing future drafts of my survey more efficiently. For example I want something like:
myvar = 100
Q1. If you have %myvar% and I take away 50 how much is left?
Q2. If you have %myvar% and I give you 70 how much do you get?
...
The more thorough the explanation the better!
You don't need any JavaScript for this. What you want to do is very easy in Qualtrics.
First, at the beginning of your survey flow assign a value to an embedded data field:
myvar = 100
Then pipe the value into your question text like:
Q1. If you have ${e://Field/myvar} and I take away 50 how much is left?
This Qualtrics Community answer might help you:
Add a function to the Look & Feel header that sets and returns the variable. Call the function from the JS in your questions.
This support article implies you can add JavaScript to any question that can set global variables, however it isn't recommended:
As with any implementation of JavaScript, we recommend abstaining from global variable creation as it can collide with existing functionality on the page.
Here's the workflow they describe (the below images are from the article):
Click "Add JavaScript" in the settings dropdown on a question, and enter your (global variable assignment) code in one of these functions:
addOnload() – Executed when the page is loaded.
addOnReady() – Executed when the page is fully displayed.
addOnUnload() – Executed when a page is unloaded (when the page is left).
As an aside, here's a good answer from Brian Rasmussen explaining the problems with global variables:
The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.
To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).
If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

Are there any disadavantages of defining global functions in javascript?

are there any specific disadvantages of defining a global function, as there are for defining global variables?
We are trying to downsize our custom JS file, and quite a bit of code is being used across functionalities.
Namespace collisions are one big issue. If you create a global function, and accidentally use the same name as another global function, you will overwrite that function, which may cause your application to break.
Bear in mind that all global variables are actually properties of the window object. If you accidentally overwrite a built-in property of window, you might produce some really odd glitches that can be hard to track down.
Another reason is just general cleanliness/organization. If you write a dozen functions to do operations on strings, you might want to put them all on an object stringOps, so that you've got them in one place.
The main danger with global references are that you will step on someone elses reference or vice versa. This can make testing extremely difficult as you may have introduced a large dose of non-determinism.
For instance say you define Global.PI as 3.14159 and your functions which ref that work fine, until a user loads a page with a library that defines Global.PI as 'Lemon', now your functions work not quite as expected.
The project I work on has global references due to the strucutre of our application.
To alleviate some of these issues we will attach a single object to window (window.yourObjHere) and place our global references within that object.
The only advantage to Globals are that some things simply can't be done without them. We have an eventBus that must message over seperate AngularJS applications. As the AngularJS native eventBus is per application, we have to register each application on our GLobal object in order to keep track of where messages should go etc. Whenver possible avoid using Globals but there are simply some things which can't be done without them. Just be careful and limit your Global footprint.
The disadvantages are as poeple ahve outlined (basically no namespacing meaning functions/variables can be overwritten) but you could get around this by declaring a global object which has all you need in it - and you can add things to it 'on the fly' :
GLOBAL_myObject = {
variableOne: 1,
variableTwo: "A atring",
getThisAndThat: function(p1,p2) {
//do some stuff
return p1 * p2; /or somthing
}
};
So refer to all your own variables as a property of that object:
alert(GLOBAL_myObject.variableOne);
GLOBAL_myObject.getThisAndThat(1,2);
Effectively you're just namespacing the variables.
to add more to the global GLOBAL_myObject you can just declare it ..
GLOBAL_myObject.anotherThing=1965; // what a year!

Javascript situations where it is GOOD to declare a global variable? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
When is it GOOD to declare a global variable in JavaScript? Typical advice concerning global variables includes:
I sometimes encounter situations where it is critical that the value of a variable is available for the duration of the activity of the user. For example, knowing the state of which page is open. Another situation is when there is a long process with lots of smaller functions, but some value needs to be maintained throughout the process. Rather than passing an argument from function to function to function, and hope it doesn't get to confusing, just create a global variable.
In general, it's bad practice to declare global variables.
Can cause problems with "Namespace Pollution".
Duplicate variable declarations of the same name inside and outside of a function.
Global variables are slower to look up than local variables.
It's easy to forget that you declared the global variable, because it's out of site from the current code you are working on.
Tracking and debugging a global variable is hard.
Asynchronous use of the global variable could cause concurrency issues.
Situations where it would be good to declare a global variable?
A constant that has a lot of characters in it, that is used a lot. Reduce the size of overall code.
Saving the state of the current condition of something that must be monitored, and available at all times to more than one function.
It seems to me that the requirements would be:
High usage and/or
Required by at least two different functions that are outside the scope of each other.
Examples:
Object with many characters:
var dc = document;
var isTheMenuDisplayed = dc.getElementById('MainMenu').style.display;
Monitor Current State:
What page is currently displayed:
/* The state of what page is currently display, must be available to
the entire application at all times.
Variable is declared outside of a function enclosure.
*/
var whichPageDisplayed = '';
function changePage(pageNameToOpen) {
if (whichPageDisplayed === 'home') {
close the home page;
open the new page;
//Make sure to record what the new current open page is
whichPageDisplayed = pageNameToOpen;
};
I'm looking for reasons about when it's GOOD to use a global variable.
If global variables are considered always bad, then how do I deal with the above two situations without a global variable?
The "Asynchronous use of the global variable could cause concurrency issues" reason shouldn't be exclusive to global variables. Asynchronous use of anything could cause concurrency issues, so I don't see how that is an argument against global variables.
The "It's easy to forget that you declared the global variable, because it's out of site from the current code you are working on" reason seems like a coding discipline issue. If I saw that there was no var = thisVar statement anywhere to be found in that section of code, I'd think to myself, "Maybe I declared it as a global variable?". Then I'd do a search to find it.
"Tracking and debugging a global variable is hard" I have a "Search All Files" option in my code editor. It searches all the files, and shows me every line of code where the search found a match. It's not that hard. Depending on what browser and what developer tools I'm using, an error msg may show me the exact line of code where the error came from.
Reducing the overall code size isn't a valid reason. Minifiers will knock it down. Besides, if you have something like your example of dc.getElementById('MainMenu').style.display, you want a method to help you. Such as getDisplayStyle('MainMenu'). Doing that is just good practice, as it allows you to keep the logic in one spot.
Saving state isn't really a valid reason either. Keep your code in modules. For example, your code turned into something a bit "better":
PageState = {
changePage: function (pageNameToOpen) {
if(this._currentPage == 'home') {
/*******/
}
this._currentPage = pageNameToOpen;
},
getCurrentPage: function () {
return this._currentPage;
}
};
PageState.changePage(pageNameToOpen);
The only times you should consider a global variable is if a library requires it, or if you need to setup configuration options on something before that "something" exists (and you are not using AMD type modules). For example, one of the popular WYSIWYG editors out there looks specifically for a global variable that defines some constants for setup.
Basically, for almost every possible usage of global variables, there is counter argument for wrapping it in a module of some sort.

Javascript variable reuse?

Is it OK to reuse variables for different data types in terms of performance and memory usage ?
What happens to old data, is it garbage collected immediately after type casting ?
It's OK to reuse variables, although unless you're doing some crazy things (say so in the question) with the amount of variables you're using, you probably should not reuse them too liberally in this way. It's considered good coding practice in general to have a variable declared to point to a specific thing, and use a different variable when you want to refer to something else.
"Variables" in Javascript are just references. They're not inherently expensive-- they don't take up more space than their text in the code and a few bytes in memory pointing to somewhere else. If you reuse a variable name by setting the reference to something else (or null/undefined), then the GC will know that that original reference is detached and know that it can be collected.
The GC in whatever browser or environment you're using will choose when to actually run the collector based on lots of factors.
Full disclosure: I have no knowledge of the internals of any particular JavaScript engines. I'm going from general principles of VMs and interpreters.
Usually, variable names just refer to other memory locations. So, whether you remove an old variable (which happens when it goes out of scope) and introduce a new one, or replace the current contents with a new object, doesn't matter much in terms of memory allocation.
Garbage collection might be different in each implementation. Immediate garbage collection is difficult; the only way I can think of doing it involves reference counters, and it's tough to make that work even for cyclic data structures. So, most garbage collectors in the wild do non-immediate collection cycles where, each time, a whole bunch of data gets removed. The cycles might, for example, be run automatically when memory use goes above a certain threshold within the engine (but it'll usually be more refined than that).
JavaScript is a loosely-typed language, and can store any datatype in any variable (even reused ones).
If you are combining types, though, you should check them periodically using the typeof keyword to ensure they are the type you think they are (for instance, trying to perform a mathematical operation on a string will concatenate or break, depending on the situation).
Furthermore, JavaScript variables stick around as long as they are within scope. Once a scope is left, the variables within it are destroyed (eventually - it's automatic and transparent). As far as garbage collection on reassigned variables, the old value is destroyed as soon as the new value is assigned.

Javascript Function Scope

This is perhaps a dumb question, but I am new to Javascript and desperate for help.
If the Javascript engine will look for global variables outside of a function, then what is the point of passing parameters to it? What do you gain?
I understand that global variables are generally frowned upon, but I still don't understand the purpose of passing variables. Does it have something to do with data encapsulation?
There's a few magic words that are used by programmers to describe different kinds of functions. Here's a few:
Re-entrant
ThreadSafe
Referentially Transparent
Idempotent
Pure
Side-Effects
You can look some of them up if you want a headache. The point is that Computer science and engineering progress has always been about reducing complexity. We have spent quite a lot of time thinking about the best way to write a function to achieve that goal. Hopefully, you can stuff tiny bits of your program into your head at a time, and understand those bits, without having to also understand the overall functioning of the entire program simultaneously, or the detailed implementation of the insides of all the other functions. A function that uses global variables can't do that very well because:
You can't guarantee that the global variables exist
You can't guarantee that the global variables are what you think they are
You can't guarantee that other parts of the program haven't modified those variables in a way you didn't expect.
You can't easily generalise to use the function multiple times on multiple sets of variables.
You can't easily verify that the function works as advertised without first setting up the function's external environment and its dependencies.
If the global variables have changed in a way you didn't expect, it's really hard to track down which part of the program is the culprit. It could be any of 500 different functions that write to that variable!
On the other hand, if you explicitly pass in all the data a function needs to operate, and explicitly return all the results:
If something goes wrong with any of those variables, it's easy to find the source of the problem
It's easier to add code to verify the "domain" of your inputs. Is it really a string? Is it over a certain length, is it under a certain length? Is it a positive number? is it whole, or fractional? All these assumptions that your code needs to operate correctly can be explicit at the start of the function, instead of just crossing your fingers and hoping nothing goes wrong.
It's easier to guess what a particular function will actually do, if its output depends only on its input.
a function's parameters are not dependant on the naming of any external variables.
And other advantages.
if you were only going to use global variables that the functions worked on then you'd always have to know the inner workings of the functions and what your global variable names had to be for them to work.
also, something like Math.abs(n) would be hard to call twice in one line if using global variables.
Functions are reusable components of your code, that executes a particular snippet on the provided variable exhibiting varying behavior.
Encapsulation comes from being Object Oriented. Functions are more for giving structure to your program.
Also, you shouldn't undermine the execution time of a method, if the variable it access exists in the context rather than being global.
If you don't need parameters to be passed to functions, then, you really don't need functions.
Functions are usually (and should be) used to provide code re-use -- use the same function on different variables. If a function accesses global variables, then every time I use it it will perform the same action. If I pass parameters, I can make it perform a different action (based on those different parameters) every time I use it.
One of the main benefits is that it keeps all the information the function needs, nearby. It becomes possible to look at just the function itself and understand what its input is, what it does, and what its output will be. If you are using global variables instead of passing arguments to the function, you’ll have to look all over your code to locate the data on which the function operates.
That’s just one benefit, of many, but an easy one to understand.
Global variables (in any language) can sometimes become stale. If there is a chance of this it is good to declare, initialise and use them locally. You have to be able to trust what you are using.
Similarly, if something/someone can update your global variables then you have to be able to trust the outcome of what will happen whenyou use them.
Global variables are not always needed by everything so why keep them hanging around?
That said, variables global to a namesapce can be useful especially if you are using something like jquery selectors and you want to cache for performance sake.
Is this really a javascript question? I haven't encountered a language that doesn't have some form of global variables yet.

Categories