1

(I am Javascript Beginner)

While I am learning Javascript global variable's life time, it say:

The lifetime of Global variables starts when they are declared, and ends when the page is closed.

I read that Javascript will store the global variable into window object? And when will it be destroyed? After I close the tab in web browser?

For example: If abc.com/page1.html create a global variable, after that in the same tab, I navigate to abc.com/page2.html will the global variable still there? How about if I navigate to another domain in the same tab, for example, another.com/page1.html?

Sam YC
  • 10,725
  • 19
  • 102
  • 158
  • (a) Create var on page1, navigate to page2 - No. You had to close page1 to open page2 (b) see [a] – enhzflep Sep 30 '12 at 06:25
  • 1
    In the future, `localStorage` and `sessionStorage` will be better supported. I don't know it's real viable right now, though. – Jared Farrish Sep 30 '12 at 06:27
  • @Jared Farrish: There's [this](https://gist.github.com/350433), but then [this](https://hacks.mozilla.org/2012/03/there-is-no-simple-solution-for-local-storage/)... – elclanrs Sep 30 '12 at 06:29

2 Answers2

3

Once window is unloaded all your JavaScript variables are lost, let's say you move from page 1 to page 2, on window leaving your variables are lost, same applies if it's on same domain or cross domain

1

No, the global variables aren't available from one page to the other. If you need to preserve data between page, you need to maintain state.

Maintaining state involves using either cookies or query string values. My answer to How to use JavaScript to fill a form on another page explains this in depth.

Community
  • 1
  • 1
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
  • So what does the lifecycle of the global variables tied to window look like? I tried setting a global variable to the window, closed and reopened chrome but the variable was still there. – Amit Kapoor Aug 23 '18 at 19:24