1

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>
john2lob
  • 123
  • 1
  • 8
  • The part that was unexpected for me was the very first load where name was nothing - every page load since it's been initially Joe as I would expect! – Jaromanda X Aug 05 '16 at 01:49
  • 1
    The script is colliding with a predefined global, [`window.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name). If you're just refreshing the page, the window hasn't changed and it can remember the name given to it. (You can wrap the full contents of the ` – Jonathan Lonowski Aug 05 '16 at 01:54
  • @JonathanLonowski: Wow, that's interesting. Never knew this behaviour of the window object – slebetman Aug 05 '16 at 02:51
  • Thanks for the answer. For those of you who want to try the example above : to refresh the page right click and choose "reload frame". – john2lob Aug 06 '16 at 00:00

0 Answers0