I'm teaching an undergrad course in CS and I selected Javascript as a language because it is so light weight. I tried to write code and test it for the basis of all my lectures. Today I discovered that I had not correctly understood the output from my own code. I had fallen prey to the fault of thinking that because JavaScript is syntactically similar to a lot of other languages, it would handle scope like those languages. Apparently not. I have a couple of oddities and I hope someone will be able to explain. The whole of the code in question is below.
<html>
<script>
function loadme()
{
contents.innerHTML="See this?";
contents = 7;
var tents = 7;
other();
}
function other()
{
var otherTents = 7;
}
</script>
<body onload="loadme()">
<p id="contents"></p>
</body>
</html>
Question 1. Apparently the identifier contents in the first line of loadme refers to the p tag with that id. This seems to be consistent across browsers and suggests that there is an automatically generated set of variables which correspond to the ids of all HTML tags on the page. I didn't even know this was possible. And if not to make matters more confusing, I can overwrite the variable with any value because javascript is not strongly typed. Please if anyone has a reference to more fully explain this feature of the language, I would appreciate it.
Question 2. Although the variable tents isn't declared until the 5th line, if I examine the code at the first line it would appear to be in scope (even if the value is undefined). That's not particularly helpful. I originally considered that to mean the variable was not in scope. Now compare that with the otherTents variable which in Chrome is shown as "not available". Then tents is available? IE is less helpful in saying that tents=undefined while otherTents is undefined. Again, if anyone has a useful reference explaining what is going on with the Javascript scope, I would appreciate it.
UPDATE UPDATE UPDATE UPDATE
There have been a lot of useful references on hoisting and I appreciate the pointer to the duplicate question on named elements. Very helpful. If I may follow up with a sub question to #2 does anyone have a comment on the non-standard handling of scope by the browsers. It seems that Chrome is at least distinguishing between out of scope and hoisted-but-undeclared. IE is less specific. Any thoughts?