How to Not Hate JavaScript: Tips from the Frontline

In my work assisting teams with JavaScript related problems, I’ve noticed some common issues. If you're experiencing frustrations with the language too, this article might be of some assistance. Disclaimer: a few of my tips might be obvious to some of you, but hopefully you’ll find at least some useful nuggets of information here! These pointers are especially useful when dealing with enterprise applications and CMS solutions. This is where we have our code, the CMS code, the code from that team nobody wants to mention...and, of course, all of them are loaded asynchronously.

The Debugger Statement

This is one of the most underused features when dealing with JavaScript, especially since it’s supported by the majority of browsers. The debugger statement was part of the first edition of ECMA Script so it's been here for quite some time.

Fundamentally it’s a simple way of adding a breakpoint. If we have code where we loop over an element list and then process the elements...

...we can add the debugger statement inside the loop so that we have a breakpoint on each iteration:

The triggering of the breakpoint happens when the execution of the code is done in the place where we have added it. In cases where there is no debugger handler - for example in most browsers without dev tools - this statement has no effect.

On the dev tools side, it will appear as if we have manually placed the breakpoint.

Of course, this is not for code you want to leave in production, but it is an extremely useful feature during the development period. It has been a life changing feature for me, especially when dealing with the vendor based JavaScript and a whole lot of callbacks.

There are also plenty of JS logging frameworks. Proper logging is essential in most programming languages, and JavaScript is no exception to this. Note that not all logging functions are standardized, and you might need to provide fallback for certain browsers. For reference, there is a more extensive article regarding logging in the real world here.

Overview of JS objects using Console.table()

Often we load data from various services and want have a nice view of it on our console - especially when the data is represented as a list of objects. For example, if we were to load a list of beers from openbeerdatabase.com (yes this database exists, and it is awesome). Using the HTTP GET beers, http://openbeerdatabase.com/documentation/beers-get call we receive a list of objects. After receiving the list, we just print it out using console.log:

The resulting list is difficult to navigate in the console. It’s tricky to get a clear picture of what the data represents. Even if we were to loop through the data, it would still be tedious. Same goes for any large JavaScript object or a list.

If we were to replace the console.log with console.table and make the call again we'd get this:

Obviously, the data is shown in a table and it is now sortable using the attributes of the objects. This makes the navigation easier. For example, this is a simple way to visually compare two arrays:

console.table([[1,2,3], [2,3,4]]);

would result in more clear version, especially if we had more sub-arrays:

Getting the Call Trace

Sometimes we want to know the call trace, aka "Who called my function". This is often visible when we get a failure - but even on success, we could get the call trace using console.trace :

Note that console.trace is a non-standard functionality and is not something you should have in production. It is, however, supported by major desktop browsers.
Async Call TraceConsole.trace works just fine for normal function calls. In most developer tools, we get the same call trace when we stop on the breakpoint. When the call is async(callback) this information is not available because the scope of the closure(callback function) is limited to the data that it holds. Fortunately, in the newer version of Chrome dev tools we have the flag async. So what previously would have been a portion of the call information...

...now becomes a full call trace containing the scope of the caller and the callback:

Most definitely an essential feature in today's asynchronous world, in my opinion. For an extensive explanation of how the async call trace works, I recommend this HTML5rocks article.

Who’s Changing My Object?: Objects.observe + console.trace

Sometimes objects get some of their properties changed, but we cannot figure out the cause. In this case, objects.observe comes to the rescue. Let's say we want to check for all changes to our person object:

Since we have combined this with the console.trace, we can also see the call trace. Awesome right?

Well, not so much, since at the time of writing only Chrome supports this and it is a non-standard functionality. Fortunately, it is proposed as part of ECMAscript 7. There is also a similar internal variant for this in Gecko based browser object.watch. Then again, when it comes to debugging, anything we can get is useful. Note that Objects.observe primary function is not debugging, but it is a great side effect.

Who’s Changing My DOM/HTML Element - Aka, Who’s F***ing Up My Code?

In complex applications, we may end up in a situation where we do not know how a certain HTML element got changed, moved, added, or had some of it's attributes modified. One way to figure out is to attach the now deprecated mutation event listeners. The API for this is far from ideal, and there are other shortcomings. The newer browser version comes with an object called MutationObserver, which enables us to watch a certain DOM element.

Suppose we wanted to list all mutations on the entire document, where the document can also be any DOM element selected:

There is also the non-programmable solution we can use in Chrome called DOM breakpoints which still uses mutation events in the background.

Server Side Logging of Client Side Errors

As simple as that, just add the error handler to the window object and you're done with the client side. The handler can then make an AJAX request to a REST endpoint which will store the error information on your server. You might find out that a client using IE 8 has a lot of issues this way because IE versions predating 9 have no string.trim(). I guess string trim is just not that essential.

Anyway, this what the most basic server side logging of client side errors might look like:

Of course, this is the most basic of solution you can have. There are tons of better solutions out there like http://www.stacktracejs.com/ or http://jsnlog.com/ and a more extensive article on Mozilla hacks. There is also a great Hacker News discussion on this topic, but hey, this is certainly a good start!
Use Google Or Other Analytics Tools to Store Data

I know you are way too busy to be writing any backend code. so why not just store the data in Google Analytics?

You can certainly do this, but note that this is a hack, and there are a lot of better commercial options out there like http://usersnap.com if you want to be really thorough - but even a hack is better than no information, which is what most people have.

So, You Don’t Think JavaScript is “Real” Code?

I had been mulling over this idea for a long time, when, a few years back, I realized that I was making a huge mistake in my approach to JavaScript. You should take it just as seriously as Java, C# or Ruby.

Diseases are something you pick up, JavaScript is something you have to learn.

Just like other programming languages, you need a book, programming exercises and multiple projects. JavaScript also needs coding style guides, testing frameworks, and code analysis, and so on. Basically everything that you have a "real code". There are complete solutions like Yeoman and JHipster that will help you with full integration.

Unless you do this, you will always end up hating JavaScript - which is a shame considering that JavaScript is all around you! If you follow best practices, most of the time you won't be debugging any code nor resorting to clever tricks. Unless you’re Chuck, that is.

Popular posts from this blog

It is always tempting to add custom attributes in HTML so that you can use the data stored there to do X. But if you do that there is no way of knowing if your HTML attribute will not be overridden in the future and used for something else and additionally you will not be writing valid HTML markup that can pass HTML 5 validator and with that you can create some very bad side effects. That is why there is a spec in HTML 5 called custom data attributes that enable number of useful features.

You may go around and read the specs, but the basic idea is very simple, you can add any attribute that starts with "data-" and that attribute will be treated as non-visible data for that attribute. By non-visible I mean that it is not something that gets rendered to the client so it does not affect the layout or style of the page, but it is there in the HTML so in no way this is private.
So let's get right into it, the following snippet is a valid HTML5 markup

Spring Rest Templates are very good way of writing REST clients. By default they work with basic HTTP so if we need to use Basic Authorization we would need to init the rest template with custom HttpClient. This way the Rest Template will automatically use Basic Auth and append to the HTTP headers "Authorization: Basic BASE64ENCODED_USER_PASS".

Sometimes we want to create a temporary file, whether to save some data that gets written by some other application or just to temporary store stuff. Well, usually applications have their own temporary folder where they do this and it gets somehow configured. But why not use the underlying OS specific file like "/tmp/" in Linux so there must be some system property that has this info and there is. The key is "java.io.tmpdir" resulting in "/tmp" in my case or by code:
String tempDir = System.getProperty("java.io.tmpdir");
We can use tempDir folder as a temporary place to store files, but there are a lot nicer ways to work with files like this even in JDK6 not just in JDK7:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class TempFile {
public static void main(String[] args) {
try {
// create a temp file
File tempFile = File.createTempFile("old-file",…