Click here to Skip to main content
15,917,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the query-
Javascript global variable is available in all pages of the application or global to the same page? Can i access and update from different page?

If i can access in other page- then how can i declare a variable just for a particular page?

If not accessible-then how can i declare a variable available in all pages?

Yes, you can have global variables. If you define a variable outside the scope of a function then it is global to all JS files loaded at that time. I think there are likely very few instances where you want to do this so make sure you rethink the design you are doing.
Share this answer
You can't create a global variable in js. You'd have to use cookies or local storage to persist data.
Share this answer
ZurdoDev 4-Aug-15 8:31am    
A global variable in JS is accessible to any JS file that is currently loaded. Sometimes referred to as global variables so it is doable but not in the same sense as other languages necessarily.
F-ES Sitecore 4-Aug-15 8:44am    
I'm pretty sure he means "global" in the sense of a persisted variable across all page requests, not "global" as in global to all scripts on that page.
ZurdoDev 4-Aug-15 8:51am    
In that case you are totally correct.
Sergey Alexandrovich Kryukov 4-Aug-15 10:48am    
Of course you are right. The problem of global variable for all scripts does not even exist, because there are no separate multiple scripts. Logically, all scripts of the same page behave as merged in one.
Please see my other comment and my answer.
Sergey Alexandrovich Kryukov 4-Aug-15 10:47am    
Not in general case. Even if you have a global variable in one single page, its most recent value will be lost if you just refresh your page.

Most universal approach is using Web storage (localStorage or sessionStorage objects), because you don't need to have or assume you have server part, server, etc. Please see my answer.

Pages, in general case, are independent from each other, from the standpoint of the client side. To share data between them, you can use Web storage:[^].

This is the newer API (current W3C candidate recommendation of June 2015:[^]) implemented by all major browsers and often overlooked. At the same time, this is the most universal approach available.

See also:[^],[^],[^].

To use the same single key for whole complex data structure, you would also need serialization you can achieve using JavaScript native JSON object:[^].

To demonstrate the technique, I dedicated a section of my article JavaScript Calculator, 7. Dynamic Strict Mode Switching and Web Storage.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900