Tuesday, January 19, 2010

'null' is null or not an object Javascript error

I spent several hours debugging an error that gave this exact error message: 'null' is null or not an object. Well, duh! The problem here is that the project was an ASP.Net project, with a large number of files that interacted in innovative and weird ways with the ASP.Net Ajax framework. So going line by line was a problem. Also, the Javascript debuggers stopped in a finally block that had nothing to do with the error.

As a side note, the only debugger that showed where the error originated was the Chrome debugger (and probably the FireFox one, but I didn't get to try it). The problem with Chrome is that it only gave me the file and line number in a "minimized" js file, so I had no clue on what was happening.

Ok, to cut it short, the error appeared in a line like $get('someId').value=... An element with the id someId did not exist, therefore the result of the function was null. Setting the value resulted in the error.

Conclusion: 'null' is null or not an object is an error that occurs when member access is requested on a function result without it being stored in a variable. Look for stuff of the form someFunction(params).member. It is a bad form anyway; store the someFunction result in a variable and then access its members: var x=someFunction(params); if (x) //doSomethingWith x.member