What is the best way to handle global variables when they are necessary. For example JSON that is inserted server side with PHP into the web page. var data = <?php getData() ?>
There seems to be 3 options.
1 leave it for garbage collection
2 leave off the var initialization of the variable and delete the variable
3 just set the variable to null and again leave it to GC.
Or there may be some other way that I haven’t thought of I am open to suggestions. Though I would prefer not to use ajax in this situation. Also, it is not feasible to insert the variable data inside of the actual javascript code because I minify it.
EDIT:
The reason I am asking is the data could be potentially large and I was wondering what is the best way to deal with it. Also, I am not sure how long garbage collection takes; so maybe it is really a non-issue. I don’t know?
Imagine that
var data = {...}was embedded in the JavaScript and did not come from PHP — where would be an appropriate place to put that?This doesn’t change and generally should be “smallest applicable scope” which may very well be a global window property — although I would generally argue against this as I favor “modules” or other designs.
There are some potential issues to watch out for wrt. closures, unintentional bindings and very (100MB+) large structures. If the data is loaded-once then not needed anymore then, by all means, let the object become unreachable (through scope termination — my preferred approach — or assigning null to the variable referencing it, etc) but for the most part:
Happy coding.
Remember:
deletedoes not destroy an object and variables are not GC’ed (they can, however, keep an object reachable). Objects are only GC’ed when: