Debugging and checking what variables are equal to in production - javascript

So I've been coding for a while now in school, and I'm having my first introduction into a real working code base at my new job. When it comes to debugging, like if I want to find out what a certain variable is equal to, I'll often just console.log() things out and hope that something useful comes out of it.
It seems really inefficient considering how many moving parts there are in the code. Most of the time, it works eventually, but it feels so barbaric just editing the code over and over and looking at the browser's console until something useful comes out, and it feels like there has to be a better way to debug in a production environment. I am specifically using Ember.JS, but this question would apply to any framework like React or Angular or Node.

There are many tools out there to debug JS, the most "basic" being the debugger in your browser. Some tools go further also, for example VSCode has a slew of extensions that open and control the browsers debugger.
Chrome: https://developers.google.com/web/tools/chrome-devtools/javascript/
Firefox: https://developer.mozilla.org/en-US/docs/Tools/Debugger
Edge: https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide/debugger
Safari also has one in the develop menu but there is no site describing it in detail - it is located in the sources pane

If you use VS Code, you can run Node apps in debug mode then select Node.js.

Related

Advice for experienced developer trying Javascript for the first time

I'm very experienced in C/C++/Objective-C and over the last few days have been trying my hand at html/css/JS and am finding it very frustrating.
Time and time and time again I've been caught out as I've a syntax error or undeclared variable due to copying / pasting etc. with the consequence being that the code suddenly stops working then I have to scratch my head and figure out why.
The most painful thing is resorting to sprinkling alerts in the code everything something fails in order to track down the reason. I know there is the new console object for logging but it doesn't seem to work with Komodoedit or jsFiddle? Which is what I've been using.
Is there a way of using these tool, or alternative tools where I can step through the code line by line in a debugger like I can with other languages? Or any tricks for easy detection of problems with the code before executing it in addition to jslint?
[I don't want to use any libraries that might have built-in support for logging etc. as I'm finding they (well JQuery/JQuery mobile is) are drastically slowing down loading times on an iPhone so want to concentrate on pure JS.]
[My target browser is just iOS, but am using Komodoedit with Chrome most of the time and every few hours try it on an iPhone]
Thanks
You need several tools.
First, get yourself a real debugger. I use the one built into Chrome. There's a similar one built into Safari and Firebug available as an add-on for Firefox. This will allow you to set breakpoints and step through your code and see exactly what is happening.
Second, get very used to running your code through jsLint. This will show you many obvious typos and encourage you to write robust code from day one.
Third, start writing in strict mode. This will again prevent some obvious typos and force you to start some good habits.
Fourth, use console.log() when needed. Once you have a debugger, it's output will show in the debug console of the debugger for any page in your browser, including jsFiddle pages. You will have to invoke the debugger on the right frame in jsFiddle and then it will work fine. I use both a regular debugger and console.log() all the time with jsFiddle. It takes a little figuring in jsFiddle and the debugger to find where your own code is to set breakpoints, but once you find it, it's easy to use.
Fifth, javascript is simply not C++. While the syntax will seem quite familiar, the way you do things with anonymous functions and closures and objects and prototypes is very different. As one who programmed in C++ for many, many years before learning javascript, I very much appreciate what I can do now in javascript that was a lot more work in C++, but it took awhile to get my brain into a new mode of thinking. I spent too much time in my first years of javascript development trying to emulate C++ techniques rather than just learning the better way to accomplish the goal in javascript.
Sixth, you will have to change how you write and test code because of the lack of a compiler that finds errors for you. I remember in the days of C++, when I needed to refactor something, I could make a bunch of changes and then let the compiler find all the other places I need to fix the syntax. You can't do that with javascript. When you make mass changes, you can run through jsLint to find some issues and then you literally need to execute every path to make sure everything works. It is a bit of a pain.
Seventh, find a strategy/tools for unit testing. Once a project gets more than a few functions long, you will benefit greatly from building unit tests that you can run anytime you make significant changes. They will both find issues for you in a lot less time than without the unit tests and they will give you the courage to refactor and clean up your code when you see the need for that because you know the unit tests will tell you if everything is working again. It's extra work up front that pays dividends many times over down the road.
Firefox has an add-on called FireBug that is very helpful for debugging CSS/javascript, and yes, it does have the ability to step through a script as well as a command line where you can try out various javascript expressions. I'm pretty sure Chrome has a similar feature.
Here is the article in which you get a list of tools to debug the javascript
advance-javascript-debugging-techniques
Since you're using Chrome, you just need to open the developer console (spanner -> tools -> javascript console, or Ctrl+Alt+J (at a guess)). Instead of sprinkling your code with alerts, use console.log, console.error, and console.info to print to it. All of those are variadic, so you can pass as much to one call as you need.
In addition to this, you can use the console to test and modify parts of your code on the fly, or to just try out a few snippets to see if they work. It's a fully functional REPL that also works with the current document.
In the sources tab of the developer console, you are able to set breakpoints and step through your code, analysing state at each point. This page goes into some detail about it: http://chromedevtools.googlecode.com/svn-history/r421/trunk/tutorials/breapoints/index.html
In the elements tab, you are able to set breakpoints on changes to elements in the DOM, including changes to attributes and child nodes. Right click a node and select the option you want. This will come in handy when debugging code that is asynchronous and plays with the document (eg. AJAX calls inserting new content).
In addition to this, you can scroll to the bottom of the styles pane to the right, and open the event listeners section. Here, you can inspect all the events bound to the selected DOM node.
You can enter debugger (without a semicolon) into your code, and it will open the sources tab at that point so you can inspect the code further. I think this may be Chrome specific.
Finally, tools like JSlint will help you spot undeclared variables as you code, as well as cases where the formatting of your code creates unexpected errors, and some might even go as far as using syntax highlighting to make you notice variables that are undefined.
This is also just scraping the surface. Your editor and JSlint can make your code look right and parse without error, but the browser and its console is where you will spend most of your time.

Is it possible to follow JavaScript in real-time?

I would like to see what the JavaScript interpreter is doing in real-time, which line it is reading and which function it is running, because I would like to make a full debug on every little piece of the JavaScript to make it faster. For this I need some tool to tell me what the interpreter is doing exactly, if it is defining a variable, if it's running a function, if it's in a loop, check the current intervals (defined in setInterval).
As far as I know Firebug can't do that.
Check out the javascript tab in Firebug, it's a full debugger. Set a break point and when your code hits that line you will have full debugging access to variables etc. Chrome has similar functionality in the developer tools which are included in a standard install.
If you're looking to do automated monitoring/analysis of your program, check out Chrome's Debugger Protocol. It provides a programatic API. I believe (but could be wrong) that this is what tools like Web Inspector and node-inspector are built on.
If you want something more than what the standard Firebug/Web Inspector interfaces are built on, you're going to have to either use something like this or start hacking on the internals of the V8 and Gecko JS interpreters.
As the other answer says,if you want to go step by step, setting a debug point is the way to go.
But since you seem interested in improving performance you might want to consider optimizing only the true bottlenecks in your application. To see which functions take the most to run, and other statistics you might want to take a look at console.profile() (available both in firebug and chrome).
Here is an example:
console.profile('myProfile');
//some code you want to know more about
console.profileEnd();
You can also start it manually by clicking the Profile button in the Console panel(in firebug)/ Profile panel (chrome)
In Chrome you might want to also take a look at Heap Snapshots (they tell you about memory usage).

Best ways to develop painlessly in Javascript on a local machine

I'm pretty new to workign with Javascript.
In most languages you can run the code quickly locally on your machine. From what I've seen, in JS you generally only use it via the browser, and so I've been uploading my code an viewing its effects in the browser. This has proven very tiresome. Also, if I mak one error, it seems like my JS/JQuery will just do NOTHING, instead of giving me a useful error, message, which is making it painfully slow to code in.
IS there some way to run JS locally to see that it is working as I go? And then only upload it to the web when I'm mostly done? What ways are there for me to do this? What ways aer there for me to unit test the Javascript locally? Say I have some JAML that should render as <p>HI</p>, how do I run this locally in a unit test?
Thanks for the help,
Alex
EDIT:
Thanks for all the great suggestions. I'll have to take a bit of time and go through them to see which ones best help me in my situation.
Since you're using jQuery, I assume that you actually want to manipulate the various elements on your page. So depending on your specific development enviroment, uploading it each time is probably the way to go anyway. If you can set up a dev enviroment on your local machine (not always possible) then go with that.
As an actual answer to your question, I suggest using Chrome's developer tools, it doesn't just have the console, but an element inspector, and a resource tracker (resource tracker is invaluable when working with JSON and AJAX, since invalid json will fail silently)
As far as I know, the firebug plugin for firefox (dont use it myself) has a similar feature set, so if you're more comfortable with that go with it.
Just remember, as a developer, your development (and debuggin) enviroment is just as important as the code that you are writing.
EDIT: Noticed that you mentioned unit testing. There are several unit testing frameworks out there for JS including one that integrates with firebug called FireUnit. Do a quick google search to find more if you want.
You don't need to upload the JS file to a server to test it. Just write an html and declare the js binding
<script
src="js/yourJSFile.js"
type="text/javascript"></script>
Edit the JS file in your favorite editor and then refresh the page to test it.
For unit testing the best option is Selenium. It allows you to record an interaction with the browser and then play it back.
You can use Firebug with Firefox to debug JS, and Google Chrome has a debugger built-in (use the Tools -> Developer Tools menu).
You can run Javascript from the local file on your machine in your browser, so you can skip the uploading step.
Also, I'd recommend using Firefox/Firebug combo for developing Javascript as it will be very handy, especially for the part you mentioned about not seeing what's going wrong with your code.
Even if you upload your javascript it gets downloaded back to you as soon as you visit the webpage that invoques it. Its run client side always. So stick to local and use firebug as the others have said. Google`s developer tool is quite nice too.
In the browser if you open the developer tools, follow the following steps:
1) Navigate to sources
2) Under sources, click snippet and open run.js
3) You can use run.js to write as much code as you want and run it locally only to see if your code is working or not (it will give you output on the console)
4) Also you can get used to some keyboard shortcuts to make it faster for you.
5) For small javascript codes, you can navigate to console and run your code there
If you want to do unit testing with Javascript there are extension of Firebug that can help you with that. I haven't try any of them, so I can't really tell you which one are worth considering, but you can easily find them if you search for the keyword "Firebug unit testing" on Google.
What seems to be comming on top is FireUnit. You can find some information about how it works here.
Consider Spider Monkey, which is a javascript engine separate from a browser. If what you are developing does not involve rendering to a webpage or can be separated from the rendering code (good practice!), then this could be useful.
I prefer Chrome to Firefox and I just found Web Server for Chrome.
It's just a Google App that quickly sets up a web server for you and will be set up anywhere you are logged into Chrome. It only allows file access to your current devices, or if you specify, other devices only on the current LAN.
You just point it to the directory with your index.html file and type http://127.0.0.1:8887 in your browser.
Additionally to the answers given you can use Jasmine for automated testing.
A tutorial that seems to help get started with automated testing on Jasmine is provided by Evan Hahn.
I used it and for me it works like a charm. Especially if test driven development is what you are going for!

Quick Test javascript snippet for browser compatibility

Just as we have http://www.sliver.com/dotnet/SnippetCompiler/ (link inactive on 2021-04-24) to test a C# code quickly, I can also do the same for javascript in chrome debugger tools and Firebug (firefox).
I would be more interested in a tool or some online tool which can run a small piece of javascript and tell if it properly runs in prominent browsers and the result.
UPDATE:
I'm a developer and not tester. I don't want to install all browsers on my PC. I like chrome and I can debug/test (for syntax/result) almost every javascript quickly in chrome by just clicking Ctrl+Shift+J and pasting my javascript in its console. But that will just test if it works in chrome. I'm not interested in creating a library right now. Google and Stackoverflow helps me get the greatest and latest javascript for a specific task very quickly.
I found one way. But it is not that quick and still would like to know better answer. May be some kind of tool which can do this.
One Way:-
Write your javascript enclosed in try-catch block on JsBin and create its public link. Now check your link with BrowserShots.
Write considerable amount of html (conditionally) using javascript to be able to see the difference on Images given by BrowserShots.
To propose another option 10 years down the line: I would suggest using JSHint for this.
The first page as you navigate to their site allows you to simply paste a JS snippet and get information regarding everything from potentially confusing syntax to "minimum ES version" warnings.
Furthermore, you can also install JSHint to your project and have a command to either run manually or slot into your existing build chain to do the same thing locally with custom rules.
I've also found this tool: JS Compatibility Checker, which is based on Can I use.
Could be helpful, but won't outline every issue.
You can easily make a test page to house your snippets, then try them in your target browsers. That has the added advantage of providing a central library for the snippets you do create, so you don't have to go hunting through entire directories looking for that cool little widget you created back in 2010.
Also, you can check the MDN Web Docs Browser Compatibility section if that interface is available (Eg. window.location - https://developer.mozilla.org/en-US/docs/Web/API/Location#browser_compatibility)

What coding conventions that help jQuery and Firebug work together?

I'm fairly new to both tools and need to go hardcore with both as I manage, monitor, and tweak a new site's design process. What sort of strategies should I ask be implemented that sets a good solid foundation for debugging, testing, and logging?
[to the degree that back-end stuff can play a role - it's .net mvc
thx
I would use Firebug to see how things are working with a few Firebug Add-ons.
I would use YSlow to check that you aren't downloading too much and it will make suggestions if you aren't minifying and gzipping your javascript.
I would also use FireQuery as that highlights jQuery very nicely in Firebug. I use it quite a lot these days to see what it should be firing.
Firebug doesn't rewrite XHRequests anymore but there is a bug in the latest Firefox/Firebug where if can block long running XHR calls. Details here
First off make sure you've read Firebug's docs. Some of the commands work cross-brower with other tools as well.
A simple search query will show you all available extensions for Firebug. As some people mentioned - some of them are really helpful.
Also it's important not to limit yourself to just a single tool since you will most likely be developing for multiple browsers. So make sure you take a look at webkits developer tools (Safari, Chrome) as well. Here's a good article which sums up the most popular development/debug tools.
You might want to research how jQuery/jQuery plugins are structured/organized so you have general idea how to organise your own JavaScript/jQuery code. It all depends how JavaScript heavy is your application. If jQuery just provides some visual enhancements and few Ajaxified pages here and there, don't bother. From other hand if it's very JavaScript heavy (as in a lot more site logic on client-side then on backend) I would suggest Prototype over jQuery, but it's just my opinion.
You could consider using automatic tools to build your JavaScript if you have a lot of code.
For example:
Sprockets
Juicer
On production server you want to end up with as few JavaScript files as possible and make sure to compress em.
If you're interested in more links to articles/tools for javascript heavy applications, drop a comment. I'm just trying to stay on topic at the moment.
I would just give a small warning using FireBug's network monitor and AJAX together. When enabled, it rewrites some HTTP headers and breaks stuff badly (well it used too, not sure anymore).
So if anything goes ape. Check that network monitoring is disabled.
I will also add for tools FireCookie, as it goes very well with $.cookie.
When I am debugging jQuery code I am using the NET panel a lot in Firebug for all ajax requests. Very helpful to see what are you sending and what are you receiving.
Also I use a lot the comand line, to test snippets of code.
You cannot do without the console. It will be very helpful. Example:
$.get( 'url.php', {},
function(data){
$.each(data, function(x){
console.log( x ); // will log each x object to see what it contains
});
}, 'json'
);
I also suggest you install FireUnit addon. It helps you work with QUnit unit tests. Of course that is if you are planning to write unit tests but in most cases that's the very good idea.
As much as you might love Firebug, Safari's developer tools are also quite powerful, and worth checking out. It's all I use when I dev.
Worth mentioning that Safari's javascript engine is still faster than FFX's, while Chrome reigns supreme. They're playing catch-up though, so this really isn't worth caring about.

Categories

Resources