Reputation: 5189
Is it true that JavaScript automatically attempts to define undefined variables to:
document.getElementById('someUndefVarName')
As in, the following appear to be equivalent:
<div id="myUndefVar">:)</div>
<script>
alert(myUndefVar); // why does this work!?
alert(document.getElementById('myUndefVar'));
</script>
See JSFiddle example: http://jsfiddle.net/AH35k/1/
Or is something else happening that I don't understand? This really caught me off-guard as I expected some sort of error since I'm using "use strict".
Upvotes: 2
Views: 444
Reputation: 63872
Some (and only some) browsers create global vars from IDs.
This can be useful when debugging (ie in the chrome console you can just type "Blah" to access an HTML Element with id="Blah"
), but should not be relied on to work cross-browser.
Further, if you do this:
<div id="myUndefVar">:)</div>
<script>
var myUndefVar;
alert(myUndefVar);
</script>
Or this:
<div id="myUndefVar">:)</div>
<script>
alert(myUndefVar);
var myUndefVar;
</script>
Then the alert
will display the value undefined
. It will only lookup the named IDs of elements if there is no other var defined in the same scope with the same name (including hoisting, as in the second example).
Upvotes: 5
Reputation: 5189
I believe the answer to this question is well summed up as:
Browsers automatically create global variables from element IDs
A related question: javascript variable corresponds to DOM element with the same ID
This seems like a pretty bad feature, I would avoid relying on this behavior.
Upvotes: 3