Ok so I hope this is a question that isn't to basic for you guys.
I know enough jQuery to get myself into trouble, meaning I can grab elements and do stuff with it, write my own little functions for interactivity and such. But then something doesn't go as expected, before I post questions to stackoverflow and get answers that make me slap myself in the forehead I would like to debug it myself and am sick of inserting alert();
into my code. In reading up on the subject there is mention of console.log();
, console.info();
and the such but I can not find any resource that explains how to use these in real world scenarios for debugging.
Do any of you know of a good resource or tutorial (not afraid to read a book) that can explain how to use these functions for the layman. It seems that the tutorials and such I am finding are either way to advanced or just skim the surface and don't show you how to use them. I understand I can insert console.log();
and it will spit out information in the console for firebug
or element inspector
. But what if my hand baked function is doing something unexpected somewhere up the line, how do I find the problem as the browser parses the javascript.
Any help would be greatly appreciated as I feel learning this will help me understand what is going on in my code, so I can stop staring at the screen going “Why isn't this working, it worked in the jsfiddle
!”
This question is related to
javascript
jquery
debugging
Breakpoints and especially conditional breakpoints are your friends.
Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)
Essentially console.log()
allows you to output variables in your javascript debugger of choice instead of flashing an alert()
every time you want to inspect something... additionally, for more complex objects it will give you a tree view to inspect the object further instead of having to convert elements to strings like an alert()
.
Learn to use a javascript debugger. Venkman (for Firefox) or the Web Inspector (part of Chome & Safari) are excellent tools for debugging what's going on.
You can set breakpoints and interrogate the state of the machine as you're interacting with your script; step through parts of your code to make sure everything is working as planned, etc.
Here is an excellent write up from WebMonkey on JavaScript Debugging for Beginners. It's a great place to start.
I like to add these functions in the head.
window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};
Now log won't break IE I can enable it or disable it in one place I can log inline
$(".classname").log(); //show an array of all elements with classname class
Source: Stackoverflow.com