tags:

views:

219

answers:

3

Is there an easy way to find parse errors in javascript code?

Last week I was debugging a javascript problem where the first javascript function that was called gave an 'object expected' error. I later determined that this was because the browser wasn't able to parse my javascript code. I eventually solved the problem but it was a painful process that involved pouring over my code line by line, trying to find my mistake.

There must be an easier way.

+1  A: 
  1. Checking that the values passed into functions are correct and throwing your own errors if they aren't will help you track down problems faster.

  2. Safari 4 (which runs on both Mac OS X and Windows) comes with some development tools (including a debugger) that are very useful. If you prefer using Firefox, Firebug provides similar functionality.

  3. JSLint can help you track down simple errors.

Steve

Steve Harrison
+3  A: 

What browser are you using? IE8 has great build-in feature to debug javascript, for Firefox, Firebug is great.

J.W.
If the error was "object expected" then it must be IE.
Ionuț G. Stan
+3  A: 

Use a tool like Jslint or an alternative browser.

Until recently, IE was the only browser that did not have built in development assistance. Other browsers will a) not come to a grinding halt on the first error they encounter, and b) tell you what and where the problem in your code is.

My favorite "quick ad easy" way to test IE syntax problems is to load the page up in Opera. It parses code like IE but will give you meaningful error messages.

I'll clarify with an example:

var foo = {
  prop1 : 'value',
  prop2 : 'value',
  prop2 : 'value',   // <-- the problem
};

If I remember correctly: In IE6 and IE7 the code will break because IE demands leaving the last comma out. The parser throws a fit and the browser simply stops. It may alert some errors but the line numbers (or even filenames) will not be reliable. Firefox and Safari, however, simply ignore the comma. Opera runs the code, but will print an error on the console indicating line number (and more).

Easiest way to write JavaScript is with Firefox + Firebug. Test with IE and have Opera tell you what is breaking when it does.

Borgar
Jslint is exactly the type of tool I was hoping for when I made this post. Thanks.
theycallmemorty