JavaScript: Possible uses for #debug directive? - javascript

Where I work, all our JavaScript is run through a compiler before it's deployed for production release. One of the things this JavaScript compiler does (beside do things like minify), is look for lines of code that appear like this, and strip them out of the release versions of our JavaScript:
//#debug
alert("this line of code will not make it into the release build")
//#/debug
I haven't look around much but I have yet to see this //#debug directive used in any of our JavaScript.
What is it's possible usefulness? I fail to see why this could ever be a good idea and think #debug directives (whether in a language like C# or JavaScript) are generally a sign of bad programming.
Was that just a waste of time adding the functionality for //#debug or what?

If you were using a big JavaScript library like YUI that has a logger in it, it could only log debug messages when in debug mode, for performance.

Since it is a proprietary solution, we can only guess the reasons. A lot of browsers provide a console object to log various types of messages such as debug, error, etc.
You could write a custom console object is always disabled in production mode. However, the log statements will still be present, but just in a disabled state.
By having the source go though a compiler such as yours, these statements can be stripped out which will reduce the byte size of the final output.

Think of it as being equivalent to something like this:
// in a header somewhere...
// debug is off by default unless turned on at compile time
#ifndef DEBUG
#define DEBUG 0
#endif
// in your code...
var response = getSomeData({foo:1, bar:2});
#if DEBUG
console.log(response);
#endif
doStuffWith(response);
This kind of thing is perfectly acceptable in compiled languages, so why not in (preprocessed) javascript?

I think it was useful (perhaps extremely useful) back a few years, and was probably the easiest way for a majority of developers to know what was going on in their JavaScript. That was because IDE's and other tools either weren't mature enough or as widespread in their use.
I work primarily in the Microsoft stack (so I am not as familiar with other environments), but with tools like VS2008/VS2010, Fiddler and IE8's (ugh! - years behind FF) dev tools and FF tools like firebug/hammerhead/yslow/etc., peppering alerts in your JavaScript isn't really necessary anymore for debugging. (There's probably a few instances where it's useful - but not nearly as much now.) Able to step through JavaScript, inspect requests/responses, and modify on the fly really makes debugging alert statements almost obsolete.
So, the //#debug was useful - probably not so much now.

I've used following self-made stuf:
// Uncomment to enable debug messages
// var debug = true;
function ShowDebugMessage(message) {
if (debug) {
alert(message);
}
}
So when you've declared variable debug which is set to true - all ShowDebugMessage() calls would call alert() as well. So just use it in a code and forget about in place conditions like ifdef or manual commenting of the debug output lines.

For custom projects without any specific overridden console.
I would recommend using: https://github.com/sunnykgupta/jsLogger , it is authored by me.
Features:
It safely overrides the console.log. Takes care if the console is not available (oh yes, you need to factor that too.)
Stores all logs (even if they are suppressed) for later retrieval.
Handles major console functions like log, warn, error, info.
Is open for modifications and will be updated whenever new suggestions come up.

Related

Disable QML console.log() messages

We are tunning the final release of our application, and we successfully disable the debug messages in c++.
CONFIG(release, debug|release):{
message(Building in release mode. We deactivate the logs.)
DEFINES += QT_NO_DEBUG_OUTPUT
} else {
message(Building in debug mode.)
}
But, our QML javascript console.log() functions are still logging the information.
I also found this source that clearly states:
The output is generated using the qDebug, qWarning, qCritical methods in C++ (see also Debugging Techniques).
What doesnt make much sense to me, since Im already ignoring all the qDebugs()
So, the question is:
How to ignore all the console.log() ?
I just think it should be an easy task, similar to the qDebug() messages.
For any further information, please leave a comment.
Note: I know that the link is for Qt 5., but im using Qt 4.8.
Thanks in advance!
If QT_NO_DEBUG_OUTPUT successfully disables output from within Qt code, it should do the same for the C++ functions that implement console.log(). However, I believe that those feature macros are deliberately not auto-tested (too many macros, too few hardware resources to test them on), so any bug report would be closed, and you'd be encouraged to submit a patch yourself.
Another solution might be to use qInstallMessageHandler(), as mentioned in the answers to this question.
Unfortunately this doesn't help you, but in Qt 5, it's enough to disable the logging rule with the QT_LOGGING_RULES environment variable:
QT_LOGGING_RULES=qml=false
Here is what I use for a final release:
qputenv("QT_LOGGING_RULES", QByteArray("*.debug=false;qml=false"));

What are the rights ways of debugging javascript?

I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.

Define custom function in Firebug

I am a chronic user of Firebug, and I frequently need to log various stuff so that I can see what I am doing. The console.log function is a lot to type. Even if I assign it to a single letter variable like q = console.log, I have to do it every time I fire up Firebug. Is there any way to do it such that q always refer to console.log (unless, of course, I override it in my session)?
To answer your question, the functionality doesn't currently exist, however I have found the firebug developers to be very responsive in the past. Why don't you put in a feature request on their forum, or better yet, code it up yourself, and ask them to add it?
Depending on your IDE, simply setup a code snippet (I use Flash Develop, so Tools -> Code Snippets).
I believe this to be a better way than setting up redirect scripts and what not, because it stops the Firebug namespace from being polluted, and makes it easier/more consistent to debug if your debugging breaks down.
The screenshot shows me using Flash Develop, hitting Ctrl+B, then hit enter. The pipe (|) in the snippet indicates where the cursor will be placed to start typing after inserting the snippet.

Syntax errors in hard to reach JS environments

I'm making an Opera Extension. It includes a background script which fails very silently. It runs in a unique environment, so I can't take it just anywhere to check if it works (it needs predefined variables). Is there a way to debug scripts without running them. That is, checking if the syntax is correct. I want something like JSLint, that instead of telling me how my code is bad tells me where the syntax errors are.
If you only want a quick search for SyntaxErrors, you could drop the code into Closure Compiler, and just choose the "Whitespace Only" option.
It'll notify you of invalid code without any code styling analysis to clutter things up.
http://closure-compiler.appspot.com/home
If you choose the "Pretty Print" option, it'll also give you a well indented result in case the original code needed some cleanup.

Find IE-breaking ECMAScript/JavaScript errors

I work on a relatively huge ECMAScript codebase (> 60,000 LOC) and we tend to struggle a bit with detecting errors for our dreaded friend Internet Explorer (especially 6 and 7).
At the moment, I've been stuck with an issue for 3 days where my RIA renders fine in Google Chrome, Firefox 3.6, Opera and Internet Explorer 8, but fails when running Internet Explorer 8 in IE7-Mode (or with a real IE-7).
My question really is: how do you do to identify code that will produce an error in IE7?
Usually I rely on JSLint and I tend to catch the usual suspects (trailing commas, I loathe you), but in this particular case I have just re-run a linter on all my code, both source and minimized, and it doesn't yield my usual suspects. So I guess I have mistakenly introduced something that IE doesn't like (who knows, maybe I got crazy and used Array.map instead of dojo.map somewhere?) and it blows up in my face, producing nice error messages that don't help me at all ("[object object]" and " is null" where it shouldn't be, so I assume there was an error up-stream that failed silently and prevented this object from being created).
I've tried having a look at the Google Closure Linter but it doesn't yield anything special, and I don't think that the Google Closure Compiler is going to be my savior either. is there any tool (command-line, web-service or other) that can parse/run code as if it were emulating IE so we can get the appropriate errors?
Any tips are appreciated.
EDIT: Thank you for your help in trying to solve my issue so far, but what I am really just asking is if there are tools that do this sort of checks, meaning validating a feature set and syntax against a particular browser. This is the sort of thing severly lacking in the JS-world in my opinion (not so much for FF or Chrome, obviously as their debuggers are a bit more helpful).
EDIT2: I eventually found the root of my problem today (after 3 days) by going through all my code changes between two branches and realizing that the problem was actually already there but never detected before and going back through even older changes to narrow down the mess and eventually end up adding console logs everywhere until I reached a point of failure (God thank emacs for its regular expression support to add logs to every single line... heavy but works...). Fun fact though: IE swallowed an error message supposed to be displayed in the try catch block originally catching the source problem and then re-throwing it. Still don't why, but if it hadn't then that would have been a lot easier to find, as it was intended for that purpose in case it broke. Weird. Might not like deep-levels of re-throw.
I'll leave the question open as for now there are no answer to the actual question.
You might try the IE8 debugger, as #galambalazs suggests; the old debugger from the IE6 era was generally not useful.
The low-level technique I've always used is to add my own try/catch blocks around large portions of the my Javascript source to narrow down the source of error. By iteratively adjusting your try/catch blocks you can do a "binary search" through your source to locate the code that's causing an exception. What you'll probably find is that there's some code that's harmless in Firefox but which IE's interpreter considers an error. (To be fair, it's usually the case that IE's strictness is justified, and that the lax behavior of Firefox is really undesirable.)
So in other words, you'd start on a Javascript source that you suspect, or perhaps you'd do this to all of your included .js files:
// top of Javascript source file foo.js
try {
// ... all the code ...
} catch (x) { alert("Error in foo.js: " + x); }
Now, if you load the page and get that alert, then you know that the error is somewhere in foo.js. Thus, you split it in half:
// top of foo.js
try {
// ... half the code, roughly ...
}
catch (x) { alert("Error in first half of foo.js: " + x); }
try {
// ... the rest of the code ...
} catch (x) { alert("Error in second half of foo.js: " + x); }
Repeat that process and you'll eventually find the problem.
You may try Microsoft Script Debugger, or Internet Explorer Developer Tools.
For complete list of what may be different in IE 8 from the older version consult with:
Internet Explorer 8 Readiness Toolkit (offical list)
especially DOM Improvements
JavaScript in Internet Explorer 8 (John Resig's post)
Also see Web Bug Track for possible quirks.
As a final note, doing console.log on every line may help you to find a particular bug in a hard way, but considering the amount of code you should really write unit test for modules. That's the only way you can make sure that your application will actually run with different inputs and conditions.

Categories