PDA

View Full Version : JS does'nt throw error on undeclared var.



rangana
05-13-2008, 09:15 AM
Good Day!,

I've been trying to find answer on this script why it works:


<script type="text/javascript">
window.onload=function()
{
var obj=document.getElementById('toggle');
var obj2=document.getElementById('toggle2');
obj.style.textDecoration='underline';
obj2.style.textDecoration='underline';
disp.style.display='none'; //Error here
disp2.style.display='none'; //Error here
obj.onclick=function()
{disp.style.display=(disp.style.display!='none')?'none':'';}
obj2.onclick=function()
{disp2.style.display=(disp2.style.display!='none')?'none':'';}
}
</script>
<span id="toggle">Link1</span><br>
<div id="disp">
Link2<br>
Link3<br>
Link4<br>
Link5<br>
Link6<br>
Link7<br>
Link8<br>
Link9<br>
Link10<br>
Link11<br>
</div>
<span id="toggle2">LinkMe</span><br>
<div id="disp2">
link1
link2
link3
</div>
LinkYou<br>
LinkAgain<br>


...as you can see, i've commented that part where I'm expecting an error:


disp.style.display='none'; //Error here
disp2.style.display='none'; //Error here


I haven't declared disp nor disp2 yet...and for whatever reason, both IE and FF does'nt throws error, which confused me :confused:

Could someone please shed some light, as I'm totally confused.

I checked this script with DTD (http://alistapart.com/ariticles/doctype) and does throws an error, but then, I would want to know the logic behind why this one works, without a DTD :o

jscheuer1
05-13-2008, 09:38 AM
I get this error in FF:


Error: disp is not defined
Source File: file:undeclared.htm
Line: 17

IE has no problem though because the elements with the id's of disp and disp2 are seen as part of the implied document.all collection, and therefor considered defined. This behavior on IE's part can often cause as many errors as it overlooks in poorly constructed javascript code.

rangana
05-13-2008, 09:48 AM
Yes, it's throws error on FF (only) when there is a DTD.

...Could you please shed some light on why FF does'nt throws the error you quote when there is no DTD?.

...Ahh...a part of document.all, let me just search this for a while, I may find advantage on this together with its disadvantage.

jscheuer1
05-13-2008, 01:11 PM
I still got warnings in FF:


Warning: Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
Source File: file:/undeclared.htm
Line: 8

Warning: Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
Source File: file:undeclared.htm
Line: 9

Removing the DTD puts the browser in quirks mode though, so at that point it will do whatever sort of error correcting it is capable of, which is determined solely by how the browser is coded.

An example of how this can cause problems is if you have an undeclared variable with an assigned value in the global scope AND an element by that name or id.