Writing great JavaScript

I probably could have named this post something like “Writing clean, validating and portable JavaScript”, but that would be no where near as catchy. The problem with “great” is it means different things to different people. I am going to show you my idea of great which may differ from many developers views, but I hope it helps someone improve their code.

So what’s the point in this, why can’t you just carry on writing JavaScript as you have been for ages. It works doesn’t it? Well if you took the same opinion with a car and drove on 20 year old tires which will give out any day you are just asking for something to go horrifically wrong. Want an example? Here you go.

What could possibly go wrong

You are writing something that manipulates color in some way. Maybe it is a color pallet tool, some form of UI selector element that allows you to set the background of your twitter style profile. You have some code like this in one of your scripts.

So as you move your cursor across the UI element picking your color, the variable color is updated. When you hit save the contents of that variable are saved in some way, maybe by posting it back to your server in a call to XMLHttpRequest (that’s ActiveXObject('Microsoft.XMLHTTP') to silly old Internet Explorer). Now you decide that you want more color capabilities at some point in your script. So you include a micro library called “color.js” which creates the global variable color. You can see where I am going with this.

Now your color string has been replaced by a libraries object. Hello bugs and time you did not need to spend. Obviously you could fix this by renaming every occurrence of color or you could use a function wrapper to sandbox your code.

And now the color variable is kept in the scope of our anonymous function, not the global object. Thus stopping the global color object conflicting with your string. You may be wondering what this mash of characters actually does, it is pretty simple actually. The initial semi-colon saves you from people that miss out the last semi colon in their script when you concatenate files. Without it you may end up with a situation in which you basically wrote this.

Obviously that will throw an error, } followed by s does not make sense in JavaScript. The other parts of our wrapper, (function() { and }());, simply wrap our code in an anonymous function which is called instantly. It is pretty much the same as writing this.

The only difference is that main will now be in the global namespace, whereas the other method does not pollute anything.


It is pretty standard for the newer JavaScript libraries to work on both browsers and servers with the same code these days. But how can you write something that will run in Chrome, Firefox and node.js in my terminal? First you place your code in the wrapper as shown above, then you simply create an alias to the global variable of your current environment.

This will allow compressors such as UglifyJS to minify your code better, will keep any helper functions and variables private and will allow you to expose what you choose to the global object. So with the code above you could then use the class like so.


If you haven’t already I insist you read JavaScript: The Good Parts. Alongside that I urge you to run all of your code through the amazing validation tool that is JSHint. JSLint will be referred to in the aforementioned book, but don’t use that, it will be mentioned because they are written by the same man, Douglas Crockford. JSHint is a much better fork of JSLint. This tool will show you any problems with your code. Some are purely stylistic, some will fix huge bugs. It will point out extra commas in arrays that will cause IE to complain and help you speed up your code.

I recommend ticking almost every box on the JSHint site, use your common sense with the last few on the far right (i.e. don’t tick jQuery unless you are using it), and adding /*jshint smarttabs:true*/ to the top of your document, if you use JSDoc style function comments that is. Now if you run your code through that, I am sure you will get at least one error, that will probably be “Missing “use strict” statement.“ which is simple to fix. Just add 'use strict'; at the top of your function wrapper like this.

If you follow the guidelines laid down by The Good Parts and JSHint you will find and fix so many errors before they bite you in the…


This post turned out a lot longer and wordier than I first intended. That seems to happen a lot with my posts. I hope you have learned something from it though and I hope it has helped you to write better JavaScript which is much less prone to errors.

Thanks for reading!

  • Aaron

    First time I’ve seen the initial semicolon as a defensive technique. Nice. The portability is nice too. I have a little library I keep adding to but instead of “this” as the argument to the enclosing anonymous function, I used “window”. Will be updating that. Great post! Thanks!

    •  Glad you like it! I hope it helps you with your library.

  • Interesting article. I have a question for you. I like validating my code through JSLint and adding ; in front of function invalidates the code. Is there any flag that we can add while check the code quality in JSHint so it ignores first semi colon. Found a similar article like yours on  Nicholas C. Zakas blog  goo.gl/UWZW7. 

    •  Very interesting. I have never seen the initial semi-colon throw up an error in JSHint. I have just tested it and it is fine. Although if you run it through JSLint you get all sorts of stylistic errors.

      I got it validating in JSLint by adding the following flag to my script: /*jslint white: true*/

      I hope that helps!

  • Alan

    Not sure recommending private variables to solve scooping issues is a good idea, you swapped one problem for another. Making the code difficult to introspect and debug.

    Better to use a namespace an object and properties

    MyApp.color = ….

  • YourLittleBrother

    To be honest, I started off with: “You’re going to tell me not to use global variables?” 

    But by the middle I was thinking, “No, no, it’s a much, much better article than that.”

    And now I have to thank you for an interesting read.

    •  I am glad you liked it! If I had recommended not to use globals then I would be a hypocrite for using MooTools all the time 🙂

      I do think that using AMD based modules is a better solution to globals though. The allow you to return your class or function to the function that requires it rather than dumping it in the window object.

  • There seems to be a discrepancy between your first and second code snippet.

    userSettings.addEvent(‘save’, function() {
    this.saveSetting(‘profile-background’, color);

    colorPicker.addEvent(‘save’, function() {
    this.saveSetting(‘profile-background’, color);

    Is it userSettings or colorPicker?

    •  Well done for spotting that! I think that userSettings is more accurate, as in you set the colour then save it to your profile. But it is not crucial really, it is just an example. I will update it though.

  • AlexGemmell

    Quick question, why add your function via prototype rather than directly to the class?

    Why:SomeClass.prototype.foo = function() { // code… };
    Instead of:SomeClass.foo = function() { // code… };Forgive my basic understanding of prototype.  I’m sure there’s a good reason!Or is this question out of the scope of this article?  🙂

    •  Interesting question. Basically without using prototype it will not work. When you create an instance of a class, x = new MyClass() for instance, the prototype of that function is copied into a new object, so the result of the “new” call is almost a copy of the prototype object.

      If you do not use the prototype object then when you run x = new MyClass() x will not contain any of the functions. This is best explained in a fiddle though: http://jsfiddle.net/Wolfy87/SS3s6/

      Hope this helps! 😀

      • AlexGemmell

        That does indeed help, many thanks!  I’ve got a ton of follow-up questions, but I think I’ll save you the headache and buy Javascript: The Good Parts for my Kindle!

  • Using jslint is a great suggestion.  I recommend also integrating it with your IDE/text editor (for example in vim using jslint.vim), so you can see the suggestions and bug fixes inline as you’re coding.  Coding JS has gotten so much easier for me since I pulled this in. 

  • Back Office Support

    It’s a nice and great blog. I’m happy to read this, the article are also very knowledgeable.
    thanks for sharing.

  • Good informative sharing thanks

  • Well Great post i l ike it very much..and very helpful for my design project

  • would it be possible to translate your site into spanish because we have
    difficulties of speaking to english, and and there is few pictures on
    your site i’d really like to learn even more of that which you are

  • Such kind of posts are really helpful to improve our work, coding is not an easy thing when it comes to web development, a little mistake can ruin the whole project and sometimes you keep up all the night to find that.