I found a strange issue in testing closures and hoisting in a web browser.
The first time you load the page below in the browser you get an alert which says "executing name=". Clicking on the browser page gives an alert "Hey !". This is expected as only the declaration of var name_c='Joe'
is hoisted. The assignment is left in place. Click on the page a second time and you get "Hey Sam!" because name has now been assigned the value from the text box inside the closure function. Again this is expected.
Now for the unexpected (at least, unexpected for me): refresh the page. You get an alert box which says "executing name=Joe". Click on the page and you get "Hey Joe!". Click on the page a second time and you get "Hey Sam!". What is happening here? Why does Joe show up ? This happens for me in Chrome and Edge.
function name_closure(name__) {
alert('executing name=' + name__);
return function() {
alert('Hey ' + name__ + '!');
name__ = document.getElementById("txtName").value;
};
}
document.onclick = name_closure(name);
var name = 'Joe';
<h1>Hoisting and Closures</h1>
<p>
<input type="text" name="txtName" id="txtName" value="Sam">
</p>