Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear JavaScript variables on page reload?

I was doing some javascript scope tests and I faced with a problem with the values of the variables.

First I executed this code:

function changeName() {
    name = "Ronaldinho";
}
changeName()
console.log(name);

The output in console was: Ronaldinho

Then I performmed only this code:

console.log(name);

The output in console still was: Ronaldinho

I was using Google Chrome. I tried to clean cache, all options of page reload (ctrl + F5/ shift + F5 / ctrl + R/ shift + R / Right click in reload icon and "Force reload and clear cache"), clear the cache, console clear, enable de option "Disable cache (while DevTools is open)".

It only works when I close and open a new tab.

like image 732
GoldShip Avatar asked Oct 23 '15 14:10

GoldShip


2 Answers

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.

like image 53
Magus Avatar answered Oct 23 '22 08:10

Magus


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); // undefined
changeName()
console.log(name); // "Ronaldinho"
like image 30
axelduch Avatar answered Oct 23 '22 08:10

axelduch