0

I've looked at several questions asking how to remember the variable, but I'm having the opposite problem which is surprising to me.

My main.js file will have this:

console.log(name);

and I get nothing. If I try to log it in the console it returns undefined, that is expected,

now I create the variable like this:

var name = "Sandy"; //global variable
console.log(name); //returns "Sandy" which is also expected.

But now the unexpected happens. I remove the variable so we're back to this, and then I refresh the page:

console.log(name); //This returns "Sandy" still...

How is this happening and why? I thought it was cookies, so I tried it in incognito mode (Maybe I misunderstand incognito?) But it works exactly the same.

In order to make the variable go away I have to close down the browser and open up a new window.

After reading briefly about LocalStorage, cookies, and incognito, it sounds like cookies are the problem, but wouldn't I have to create the cookie manually?

It seems like the browsers should be forgetting the variables unless I explicitly set the variable to a cookie.

John Curry
  • 428
  • 1
  • 5
  • 17
  • 2
    By declaring `name` in global space you are overwriting the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) property which is presistent across page changes of the same domain. You would get the same results by doing `window.name="Sandy"` – Patrick Evans Jan 30 '16 at 20:21
  • So global variables are persistent across page changes by default? I would accept this as an answer but it's a comment. – John Curry Jan 30 '16 at 20:26
  • Possible duplicate of [var name and window.name](http://stackoverflow.com/questions/11064897/var-name-and-window-name) – Patrick Evans Jan 30 '16 at 20:27
  • No, just special properties like `name` – Patrick Evans Jan 30 '16 at 20:29

1 Answers1

1

By declaring a global variable called name you are overwriting a window.name property, which doesn't reset on page refresh.

window is a built-in object, specific to each opened tab in a web browser and represents a containing document. You can read more about the window object here and more about its name property here.

You can also check what happens during execution of your code by logging window.name before and after you define your variable.

It's best to avoid using name as a variable in JavaScript code that runs in a browser. Set your variable to something else (that is not a reserved word or a propery name of a built-in object) and your code will work.

ddbk
  • 26
  • 3