<html>
<head>
<script type='text/javascript'>
alert(name);
function init() {
name = parseInt(name) +1; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
</script>
</head>
<body>
Some Text
</body>
</html>
This is my simple JavaScript Code. I just copy/pasted the above code and refreshed multiple times to see strange output.
Every time I refresh the page, I can see name variable is increased by 1.
First load : alerts ' ' and 1
Second load : alerts 1 and 11
Third load : alerts 11 and 111
and so on ...
If I close the window or tab and then reload, it appears to work correctly. But, again, on the second reload in the same window or tab, results in the same output as mentioned above.
My question is: why and how the variable name
is available even after refresh and multiple refreshes as well (F5 or Ctrl+Shift+R)?