Skip to content
Fragmented Development

Debugging the "Object has no properties" Error in Javascript

I've encountered this problem before while writing Javascript, and was recently reminded what a pain it can be to debug. Hopefully these tips will prevent you some strife in your own coding.

Anatomy of the Error

This error occurs when you try and access an object's property, usually with dot notation, when the object does not exist or does not exist yet. For instance, accessing the "status" property of the "window" object looks like this:

var status = window.status;

The problem occurs if the object (in this case, window) doesn't exist for some reason. There are several reasons this might occur.


Are you sure you're talking about the right object? If you're trying to write the example above, but accidentally enter the following code...

var status = **widnow**.status;

...then the browser is going to be unable to find that "widnow" object and will throw that error as a result. Instead of the window object, it thinks you're referencing the widnow variable, which is initialized as NULL and doesn't have a status property.

Page Has Not Loaded

Browsers implement something called "progressive rendering", which means they'll try and display the page as fast as they get it, line by line. If you include your javascript in the head tag, then that code will be run before the browser has a chance to load the body.

If you don't reference any elements specifically, you might be able to get away with this – but you're better off playing it save and having everything run after the page has loaded. Stick all of your scripts in a function or object, and tell them to execute after the page is done loading using something like Dustin Diaz's addEvent() function.

Sneaky Bugs

The bug that got me thinking of all of this was a sneaky one. I had my code wrapped in a function called closeWindow(), that was added at the time of page load using the addEvent() function:

addEvent(window, 'load', closeWindow());

Each time I refreshed the page, I received the "object has no properties" error message. I debugged a little bit, and was able to figure out that the contents of the closeWindow() function was being executed before the page was loaded, even though I went to all the trouble of using the addEvent() function.

The culprit was the extra set of parentheses I added to the addEvent() argument. When you send a function into addEvent() (or any other function, I suppose) as a function argument, do not add parentheses after the function name! Instead of sending the name of that function, I was executing the function as soon as I called addEvent(), before the page had to load. Here's the revised code, that worked like a charm.

addEvent(window, 'load', closeWindow);

I hope this saves some time debugging a similar problem. If you find this useful, let me know!

Tags: javascript

Add Your Comment