Thursday, August 14, 2008

 

'undefined' is null or not an object

Tracking down a nasty bug in some JavaScript code I wrote has taken me a while. Granted, the actual script was slightly more complex and much longer, and I may be somewhat out of practice too.

This script worked perfectly fine in Firefox, in Seamonkey, even in Opera but failed miserably in Internet Explorer with the not so helpful error message 'undefined' is null or not an object:


var items = [
{id: 'type', condition: !document.referrer},
{id: 'link', condition: !!document.referrer},
];

for (var i=0; i < items.length; i++) {
var item = items[i];
if(typeof(item.condition) == 'undefined' || item.condition) { // Bang!
// do something useful
}


Can you see the problem (and why this works in Mozilla)?

Labels: ,

Comments:
Hi, did you find a solution for this? stumbeld over the exact same case.
 
Robert, the extra comma in the items array was the culprit.

A trailing comma should be ignored, but in Internet Explorer the items array has three elements, the last of which is undefined.

Dereferencing undefined in item.condition then fails with the error message “'undefined' is null or not an object”.
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home




Page tools




Archives


This page is powered by Blogger. Isn't yours?