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: ,

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”.

I know this is way late, but I found this post and it solved an issue I'd been trying to fix for a week! Thanks so much for posing the solution. I went back, fixed a loop that was mistakenly adding in a comma on the last entry of my array.

Thanks again!
Terri, glad you found this helpful. The comma at the end of a list tends to be difficult to spot even in the contrived sample code, even more so in a longer program.
Post a Comment

Subscribe to Post Comments [Atom]

Page tools