2

Whenever i initialize a variable called 'name' it keeps its value through pages.

Like this:

page1.html

<html>
<script>
    var name = prompt("What's your name?");
    alert(name);
</script>
    <a href='page2.html'> Page2</a>
</html>

page2.html

<html>
   <script>
       alert(name);
   </script>
</html>

So in both pages the variable name keeps the value of what it has been given in the prompt of the first page, the two pages alert the same thing, could someone explain me why this happens?

dvr
  • 885
  • 5
  • 20
  • 1
    That shouldn't happen. All variables are reset when you load a new page. – Barmar Oct 17 '14 at 04:59
  • Are you accessing page2.html through an iframe? –  Oct 17 '14 at 05:00
  • By any chance, in `page2.html`, when it alerts, does it alert but no message is shown? – Zaenille Oct 17 '14 at 05:00
  • 1
    Is this all your code, or just a section of it? – Spencer Wieczorek Oct 17 '14 at 05:00
  • It can not alert the same value which initialised in page1. You may get an alert but with no text in it. If you get alert with the specified text in page2 without initialising it there, then you surely have defined it somewhere else which is used by page2. – Pramod Solanky Oct 17 '14 at 05:02
  • ok i posted the full code of both pages. – dvr Oct 17 '14 at 05:05
  • Which browser are you using? Also, you generally should not have script tags defined outside the head or body tags. –  Oct 17 '14 at 05:08
  • im using chrome and it is just for example sorry, i know it's impossible to happen thats why im here. – dvr Oct 17 '14 at 05:09
  • @Dan, you are correct. I replicated it as well. This is very weird. Am currently researching. – Zaenille Oct 17 '14 at 05:17

3 Answers3

5

The behavior you're seeing isn't normal, and won't work for almost any other variable. name is actually a reserved variable in Javascript, which is why you're seeing interesting behavior.

All variables in Javascript are properties of the window object. If you create a variable called age, you can also access it at window.age. window.name is a special property of the current browser window that allows it to be given a name, and this value can persist between pages.

If you change the name of your variable to age, it will go back to working as expected -- the variable will be empty in page2.html.

A little more about window.name

Dan Hlavenka
  • 3,697
  • 8
  • 42
  • 60
3

The global name variable is the window.name property. It is a string that is indeed persisted across page loads in the same browsing context - if you open the second page in a new tab it should no more "work".

To avoid this, use a safe name for your variable instead, or wrap your code in an IIFE.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

It won't keep its value through pages, and the two pages will not alert the same thing.

There must be some other code in your page that sets name to some value.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247