Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does variable 'name' doesnt need to be initialized after first use [Javascript] [duplicate]

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?

like image 901
dvr Avatar asked May 02 '26 15:05

dvr


1 Answers

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

like image 134
Dan Hlavenka Avatar answered May 04 '26 04:05

Dan Hlavenka