This question already has an answer here:
- Why is window.name cached? 2 answers
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?
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 calledage
, you can also access it atwindow.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
The global
name
variable is thewindow.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.
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.