Search code examples
javascriptwindowglobal-variables

The lifetime of JavaScript global variables


I read the following on w3schools and I don´t understand what it means by the second part:

[global variables] remain available to new pages loaded into the same window.

Anyone can enlighten me ?

In a web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded into the same window.

link: https://www.w3schools.com/js/js_scope.asp


Solution

  • If w3schools really says that (heaven help us, it does), it's just plain wrong, as can easily be proved with a simple experiment.

    When a web page loads, the global environment for the JavaScript on that page is created fresh. No globals from a previous page in that same window are available to the new page. Obviously, some other things provided by the browser (such as things stored in web storage) may be, but not global variables.

    While it's improved a bit over time, unfortunately this isn't the first simple factual error people have noted on w3schools. I'd suggest using MDN's documentation instead. While MDN is community-edited and thus does sometimes have the occasional inaccuracy, over all it's quite good, and any inaccuracies one user adds tend to be fixed fairly quickly by others.

    In a comment you've asked:

    What's the official JavaScript documentation page ?

    The only "official" documentation for JavaScript is the specification. Likewise, browser features like the DOM are also documented in various specifications. The WHAT-WG "HTML5 standard" (which is about a lot more than HTML) also documents HTML (obviously) and a wide range of other browser features. Others are in their own specs. One of the great things about MDN is that it links to specs.