How to clear JavaScript variables on page reload?
If you forget the var
keyword in javascript, the variable will be created in the root object. In a browser, the root object is window
. So you'll find your variable in window.name
. If you want to delete it you can do delete window.name
EDIT : In the Chrome console, the executed code is protected from that. Chrome use an other object than window
. You'll find your variable in this.name
. So you can delete it with delete this.name
.
Change the name of your variable, try "myName" instead. Since you never use the "var" keyword, name
is in the global scope.
But something else happens: window.name
is already taken! Because a window has a name
associated with it. (see window.open
for further information)
Or better: In 99% of cases use the var
keyword to declare a variable, the rest of the time, don't declare a variable (meaning window[anyVariableName]
is not truly declaring a variable, rather than defining a new key to the window object, implicitly available everywhere in a browser's context).
The final code (if you want to keep the variable name
):
var name;function changeName() { name = "Ronaldinho";}console.log(name); // undefinedchangeName()console.log(name); // "Ronaldinho"