I'm wondering which would be better practice. Polluting the global namespace with global variables for intra-session persistence or using localStorage instead?
So in other words set a global variable on launch, change its value in a function when required and reference it in a third function, or use localStorage.setItem
then localStorage.removeItem
when the value is no longer needed?
Will doing either one increase memory efficiency?
I'm wondering which would be better practice. Polluting the global namespace with global variables for intra-session persistence or using localStorage instead?
So in other words set a global variable on launch, change its value in a function when required and reference it in a third function, or use localStorage.setItem
then localStorage.removeItem
when the value is no longer needed?
Will doing either one increase memory efficiency?
Share Improve this question asked Dec 4, 2014 at 19:39 OliverJ90OliverJ90 1,3213 gold badges23 silver badges42 bronze badges 1- 2 Check this test jsperf./localstorage-vs-globals – Lilás Commented Feb 11, 2015 at 19:45
2 Answers
Reset to default 7LocalStorage is primarily for persistent data across sessions. In your case, as your looking for an intra-session persistence, global variables have clear advantages.
I will start with cons of global variables first.
- It uses the global namespace, any third party js code can manipulate it
- A page refresh can wipe off your data
Well, that's it. If we consider the cons of LocalStorage, the list will raise your eyebrows.
- set and get are slow and can be a performance bottleneck for large datasets
- only strings are allowed; you may have to serialize your data before setting
I would surely vote up for LocalStorage if your use case involved inter-session storage. However, in your scenario, the only benefit you see is the removeItem function for which you have the delete counterpart for global variables.
This article may be helpful: http://www.sitepoint./html5-browser-storage-past-present-future/
As now consider to using DI in frameworks like Angular.