Site Meter

Monthly Archives: August 2012

Using JSHint inside Visual Studio – the basics

JSHint is great. It’s a linting tool for JavaScript: a simple tool that can very often spot your mistakes before you do. It can save you from a lot of tedious debugging, lets you refactor JavaScript code with greater confidence, and reduces the chances of you deploying broken code to your production server.

I’ve been relying on it day-to-day for the last few months while working on a large JavaScript application, and now I’d be very distressed if I had to work without this instant, zero-effort safety net. So, what does it do?

  1. It identifies definite, objective errors in your code (e.g., mistyped keywords, mistyped variable names, mismatched parentheses, and other syntactical slip-ups) before they end up in your browser.
  2. Optionally, it enforces some basic code style consistency rules (e.g., no trailing whitespace, no use of the == operator, etc.), depending on how you configure it

Feature 2 – enforcing style consistency –  isn’t hugely beneficial for small, single-developer projects. But for longer-lived, multiple-developer projects, your team will surely benefit in the long run from a few consistency guarantees.

Feature 1 – typo detection – is the killer benefit from my point of view. I’ll show you a good example in a moment.

As you can probably guess, there are two common ways to use JSHint on a project:

  • By integrating it into your build process (on a CI server). This enforces team-wide consistency.
  • By integrating it into your IDE. This gives you instant feedback as you code.

My current project uses both, but primarily I appreciate having it in my IDE. So, in this post I’ll focus on a Visual Studio extension that makes it easy. Of course you can also find JSHint plugins for many other IDEs or code editors, such as my other favourite: Sublime Text 2.

Why it matters

Here’s an exaggeratedly simple example. Let’s say you have a perfectly OK function like this:

function averageHeight(heights) {
    var sum = 0, index;
    for (index = 0; index < heights.length; index += 1) {
        sum += heights[index];
    return sum / heights.length;
var myAverageHeight = averageHeight([1.75, 1.78, 1.82]);

Now you decide you want to rename the function just to “average”, since it’s not really specific to heights at all. So you go ahead and change the function signature. But you forget to the change anything else:

function average(values) { // <-- This is the only line I remembered to change
    var sum = 0, index;
    for (index = 0; index < heights.length; index += 1) {
        sum += heights[index];
    return sum / heights.length;
var myAverageHeight = averageHeight([1.75, 1.78, 1.82]);

Now you press Ctrl+S to save the changes. In the tiniest fraction of a second, and without waiting to build your server-side code, the JSHint extension I’m about to show you will return its verdict about your file:


Well, you’re going to notice this! The first three errors tell you exactly where you’ve forgotten to change “heights” to “values”, and they won’t go away until you fix every last one. The fourth warns you that you’re trying to invoke a function that no longer exists. The fifth tells you it’s quite pointless to have this new “average” function, because nobody uses it.

Even in this simple case it’s very nice to know exactly how many times you forgot to rename the “heights” variable. You can imagine how valuable (and reassuring) it is in more complex refactorings such as extracting a function.

I’m not saying this eliminates the need for automated testing. This merely adds to JavaScript a subset of the kinds of code validity checks that you might be accustomed to in C# or another strongly-typed language.

In addition, the kinds of optional common stylistic rules that JSHint can enforce include:

Possible drawbacks of JSHint

In the interest of balance, let me try to give you advance notice of a few downsides to using JSHint, which actually apply to pretty much any linting tool:

  • It’s best when you’re writing fresh new code. When writing new code files, you can keep them compliant with your rules with little effort right from the beginning. But it’s not easy to start using JSHint on a large legacy codebase, because it will initially report thousands of violations. You can either invest a big chunk of time in cleaning everything up, or you can use /*ignore jslint */ comments to ignore your old files, removing those comments one-by-one as you clean up each file over the long term.
  • It’s reliable, but not deeply sophisticated. JavaScript is fully dynamic, so the linter can’t know whether or not a given object will have a certain property at runtime. So, if for example you’re renaming properties as opposed to variables, don’t expect JSHint to find all the places where the old property name is still referenced. Don’t get caught believing that “no JSHint errors” guarantees “no bugs”.
  • It needs a bit of configuration to give the best results. Depending on how you and your IDE work, you’ll need to toggle a bunch of checkboxes in the early days. You’ll get very annoyed if your IDE persistently inserts or reformats code in a way that violates your JSHint rules. Change the IDE settings or the JSHint settings or both.
  • You need to start tracking global variables. In the long run, this is a benefit not a drawback, but it might feel like extra work at first. If you use third-party libraries whose APIs live in a global (e.g., $ for jQuery, ko for Knockout), you must explicitly tell JSHint about them otherwise it thinks you’re referencing undefined things. Eventually, though, you’ll be glad to have an unambiguous list of your dependencies.

So, what’s JSLint and how does it relate to JSHint?

Historically, JSHint is derived from the longer-established JSLint project from Douglas Crockford. The reason why JSHint exists is just to offer more flexibility: JSHint has a modest set of rules derived from common use, whereas JSLint is stricter and requires you to code exactly like the legendary Mr Crockford does.

The following Visual Studio extension lets you choose between JSLint and JSHint with a simple config option. Try out both and see which one you like.

Integrating JSHint into Visual Studio 2010

Yes, I know Visual Studio 2012 was just released this week! We’ll get to that in a minute. Not everyone upgrades during the first week…

The VS extension I’ve been using for the last few months is called JSLint for Visual Studio 2010. It’s free and open source, and you can install it directly from inside VS. Go to Tools > Extension Manager. Click Online Gallery then in the search box (top-right), enter jslint.


Once it’s installed, you’ll find a new menu entry: Tools > JS Lint Options. Personally, I like to set it up like this:



I’m not even going to discuss the multitude of code style options represented by the big grid of checkboxes. If you’ve coded JavaScript for a while, you probably have plenty of opinions of your own.

Notice that you can export and import configurations as XML files. You’ll probably want to store a standard team-wide setup in source control.

Now when you’ve got a JavaScript file open, any time you hit Ctrl+S, the Visual Studio extension will populate the IDE’s “Error” pane with any issues it found – extremely quickly, because it already has a live JavaScript runtime loaded in memory. Double-click to jump to that line. Either fix it, or modify your config settings to make the linter more tolerant.

Issues with this extension

Of course, it’s not totally perfect. Here are a couple of minor niggles I’ve experienced with this extension:

  • I don’t see a way of making it load project-specific rulesets. This means that all of the projects you work on will need to share the same configuration (or you have to keep importing different configurations manually).
  • It collects errors from every JavaScript file you open. So for example if you open jquery-x-x-x.js to see how something is implemented, JSLint for VS2010 will freak out and report more than 1,000 errors. The errors don’t go away when you close that particular tab, so you must manually right-click on the error list and choose Clear JS Lint Errors. Not a big deal, but adds a touch of friction.

Integrating JSHint into Visual Studio 2012

Unfortunately, there isn’t yet a “JSLint for Visual Studio 2012” on the extensions gallery, or at least not one that I could find. And if you try to download the .vsix file for the VS2010 version, it won’t let you install it into VS2012:


So, how come the screenshot earlier in this blog post shows it running in VS2012? Well, I guess the extension’s developers haven’t got round to testing on VS2012 yet, but if you’re impatient and want it installed right now, it’s just a matter of modifying the “manifest” in the .vsix file to make it allow installation. Here’s what I did:

  1. Rename JSLint.VS2010.vsix to Turns out these things are really zip archives. Extract the files to a temporary folder.
  2. Open extension.vsixmanifest in Notepad.
  3. Find <VisualStudio Version=”10.0″> and change it to <VisualStudio Version=”11.0″>.
  4. Zip all the files back up, and rename the result so it has a .vsix extension.
  5. Install it.

This is totally unsupported, off piste, entirely at your own risk, and no technical support questions will even be acknowledged much less answered. But hey, it seems happy enough on my machine:


Hopefully the extension’s developers will get a chance to make VS2012 support official in the near future. Maybe you (yes – actually you!) could submit a patch. This is open source, after all.

Rich JavaScript Applications – the Seven Frameworks (Throne of JS, 2012)

A week ago was the Throne of JS conference in Toronto, perhaps the most interesting and different conference I’ve been to for a while. Quoting its website:

It’s no longer good enough to build web apps around full page loads and then “progressively enhance” them to behave more dynamically. Building apps which are fast, responsive and modern require you to completely rethink your approach.

The premise was to take the seven top JavaScript frameworks/libraries for single-page and rich JavaScript applications — AngularJS, Backbone, Batman, CanJS, Ember, Meteor, Knockout, Spine — get the creators of all of them in one location, and compare the technologies head to head.*

Disclaimer: I was there to represent Knockout, so obviously I’m not neutral. In this post my focus is on what the creators said about the scope and philosophy of their technologies, and not so much on whether I agree or disagree.

* Yes, I know that’s eight frameworks, not seven. This part was never fully explained…

TL;DR Executive Summary

  • For many web developers, it’s now taken for granted that such client-side frameworks are the way to build rich web apps. If you’re not using one, you’re either not building an application, or you’re just missing out.
  • There’s lots of consensus among the main frameworks about how to do it (Model-View-* architecture, declarative bindings, etc. — details below), so to some extent you get similar benefits whichever you choose.
  • Some major philosophical differences remain, especially the big split between frameworks and libraries. Your choice will deeply influence your architecture.
  • The conference itself was stylish and upbeat, with a lot of socialising and conversations across different technology groups. I’d like to see more like this.

Technologies: Agreement and Disagreement

As each SPA technology was presented, some fairly clear patterns of similarity and difference emerged.

Agreement: Progressive enhancement isn’t for building real apps.

All the technologies follow from the view that serious JavaScript applications require proper data models and ability to do client-side rendering, not just server rendering plus some Ajax and jQuery code.

Quote from Jeremy Ashkenas, the Backbone creator: “At this point, saying ‘single-page application’ is like saying ‘horseless carriage’” (i.e., it’s not even a novelty any more).

Agreement: Model-View-Whatever.

All the technologies made use of model-view separation. Some specifically talked about MVC, some about MVVM, and some specifically refused to define the third piece (just saying it’s models, views, and some kind of application thing that makes them work together). The net result in each case was similar.

Agreement: Data binding is good.

All except Backbone and Spine have a built-in notion of declarative data binding in their views (Backbone instead has a “bring your own view technology” design).

Agreement: IE 6 is dead already.

In a panel discussion, most framework creators said their IE support focus was limited to version 7+ (in fact, Ember and AngularJS only go for IE8, and Batman requires an ES5 shim to run on IE older than v9). This is the way of things to come: even jQuery 2 is set to drop support for IE older than v9.

The only stalwarts here appear to be Backbone and Knockout which support IE6+ (I don’t know about Backbone’s internals, but for KO this means transparently working around a lot of crazy edge-case IE6/7 rendering and eventing weirdnesses).

Agreement: Licensing and source control.

Every single one is MIT licensed and hosted on GitHub.

Disagreement: Libraries vs frameworks.

This is the biggest split right now. You could group them as follows:

Libraries Frameworks

Backbone (9552)

Knockout (2357)

Spine (2017)

CanJS (321)

Ember (3993)

AngularJS (2925)

Batman (958)

Meteor (4172) — unusual, see later

Numbers in brackets are a point-in-time snapshot of the number of GitHub watchers, as a crude indicator of relative influence.

What does this mean?

  • Libraries slot into your existing architecture and add specific functionality
  • Frameworks give you an architecture (file structure, etc.) that you are meant to follow and, if you do, are intended to handle all common requirements

By far the most passionate advocate of the framework model is Ember, whose creator Yehuda Katz is formerly of the Rails and SproutCore projects (similar philosophy). His argument was that anything less is just not ambitious enough and isn’t seriously advancing the state of the art. The counter-argument is that libraries are more focused, and hence can be easier to learn, adopt, customize, and help minimise project risk because your architecture isn’t so deeply tied to a specific external project. Based on my conversations, I’d say the audience was split and supported both sides of this debate.

Note that AngularJS is arguably somewhere in between library and framework: it doesn’t require a particular layout of files at development time (library-like), but at runtime it provides an “app lifecycle” that you fit your code into (framework-like). I’m listing it as a framework because that’s the terminology the AngularJS team prefers.

Disagreement: What’s flexible, what’s integrated.

Each technology has different levels of prescriptiveness:


URL routing

Data storage


Built-in DOM-based templates (mandatory)

Built-in (optional)

Built-in system (optional)


Choose your own (most used handlebars.js, a string-based template library)

Built-in (optional)

Built-in (overridable)


Built-in DOM-based templates (mandatory)

Built-in (mandatory)

Built-in system (mandatory)


Built-in string-based templates (mandatory)

Built in (optional)

Built in (optional)


Built-in string-based templates (mandatory)

Built-in (mandatory)

Built-in (overridable)


Built-in DOM-based templates (optional, can do string-based too)

Choose your own (most use sammy.js or history.js)

Choose your own (e.g., knockout.mapping or just $.ajax)


Built-in string-based templates (mandatory)

Built-in (mandatory?)

Built-in (Mongo, mandatory)


Choose your own string-based templates

Built-in (optional)

Built-in (optional?)

As expected, whenever a library leaves a decision open, they argue it is better overall to guarantee composablity with arbitrary 3rd-party libraries. And the obvious counter-argument is that integration can be more seamless if built-in. Again, based on my conversations, the audience was split and opinions went in all directions — usually based on how much other technology stack an individual was wedded to.

Quote from Tom Dale of Ember: “We do a lot of magic, but it’s good magic, which means it decomposes into sane primitives.

Disagreement: String-based vs DOM-based templates

(As shown in the above table.) For string-based templates, almost everyone used Handlebars.js as the template engine, which seems to dominate this space, though CanJS used EJS. Arguments in favour of string-based templates include “it’s faster” (debatable) and “theoretically, the server can render them too” (also debatable, as that’s only true if you can actually run all of your model code on the server, and nobody actually does that in practice).

DOM-based templates means doing control flow (each, if, etc.) purely via bindings in your actual markup and not relying on any external templating library. Argument include “it’s faster” (debatable) and “the code is easier to read and write, because there’s no weird chasm between markup and templates, and it’s obvious how CSS will interact with it“.

In my view, the strongest argument here came from the AngularJS guys who stated that in the near future, they expect DOM-based templating will be native in browsers, so we’ll best prepare ourselves for the future by adopting it now. AngularJS is from Google, so they are already working on this with Chromium and standards bodies.

Disagreement: Levels of server-agnosticism

Batman and Meteor express explicit demands on the server: Batman is designed for Rails, and Meteor is its own server. Most others have a goal of being indifferent to what’s on your server, but in practice the architecture, conventions, and some tooling in Ember leans towards Rails developers. Ember absolutely works on other server technologies too, though today it takes a little more manual setup.

The technologies — quick overview

Here’s a rundown of the basic details of each technology covered:

  • Who: Jeremy Ashkenas and DocumentCloud
  • What:
    • Model-View in JavaScript, MIT licensed
    • Most minimal of all the libraries — only one file, 800 lines of code!
    • Extremely tightly-scoped functionality — just provides REST-persistable models with simple routing and callbacks so you know when to render views (you supply your own view-rendering mechanism).
    • The best-known of them all, with the most production deployments on big-name sites (perhaps easy to adopt because it’s so minimal)
  • Why:
    • It’s so small, you can read and understand all of the source before you use it.
    • No impact on your server architecture or file layout. Can work in a small section of your page — doesn’t need to control whole page.
    • Jeremy seems to exist in a kind of zen state of calm, reasonable opinions about everything. He was like the grown up, supervising all the arguing kids.
  • Where: GitHub and own site
  • When: In production for nearly 2 years now
  • Who: The Meteor development group, who just raised $11.2 Million so they can do this full-time
  • What:
    • Crazy amazing framework from the future, barely reminiscent of anything you’ve ever seen (except perhaps Derby)
    • Bridges a server-side runtime (on Node+Mongo) with a client-side one, so your code appears to run on both, including the database. WebSockets syncs between all client(s) and server.
    • Does “live deployments” every time you edit your code – client-side runtimes are updated on the fly without losing their state
    • Makes more sense if you watch the video
    • Like everyone I spoke to at the event, I really want this to succeed — web development needs something this radical to move forwards
  • Why: You’ve had enough of conventional web development and now want to live on the bleeding edge.
  • Where: GitHub and own site
  • When: It’s still early days; I don’t know if there are any production Meteor sites yet except built by the core team. They’re totally serious about doing this, though.
  • Who: Yehuda Katz (formerly of jQuery and Rails), the Ember team, and Yehuda’s company Tilde
  • What:
    • Everything you need to build an “ambitious web application”, MIT license
    • Biggest framework of them all in both functionality and code size
    • Lots of thought has gone into how you can decompose your page into a hierarchy of controls, and how this ties in with a statemachine-powered hierarchical routing system
    • Very sophisticated data access library (Ember.Data) currently in development
    • Intended to control your whole page at runtime, so not suitable for use in small “islands of richness” on a wider page
    • Pretty heavily opinionated about files, URLs, etc., but everything is overridable if you know how
    • Design inspired by Rails and Cocoa
    • Tooling: They supply project templates for Rails (but you can use other server platforms if you write the code manually)
  • Why: Common problems should have common solutions — Ember makes all the common solutions so you only have to think about what’s unique to your own application
  • Where: GitHub and own site
  • When: Not yet at 1.0, but aiming for it soon. API will solidify then.
  • Who: Developed by Google; used internally by them and MIT licensed.
  • What:
    • Model-View-Whatever in JavaScript, MIT licensed
    • DOM-based templating with observability, declarative bindings, and an almost-MVVM code style (they say Model-View-Whatever)
    • Basic URL routing and data persistence built in
    • Tooling: they ship a Chrome debugger plugin that lets you explore your models while debugging, and a plugin for the Jasmine testing framework.
  • Why:
    • Conceptually, they say it’s a polyfill between what browsers can do today and what they will do natively in a few years (declarative binding and observability), so we should start coding this way right now
    • No impact on your server architecture or file layout. Can work in a small section of your page — doesn’t need to control whole page.
  • Where: GitHub and own site
  • When: In production now (has been at Google for a while)
  • Who: The Knockout team and community (currently three on the core team, including me)
  • What:
    • Model-View-ViewModel (MVVM) in JavaScript, MIT licensed
    • Tightly focused on rich UIs: DOM-based templates with declarative bindings, and observable models with automatic dependency detection
    • Not opinionated about URL routing or data access — combines with arbitrary third-party libraries (e.g., Sammy.js for routing and plain ajax for storage)
    • Big focus on approachability, with extensive documentation and interactive examples
  • Why:
    • Does one thing well (UI), right back to IE 6
    • No impact on your server architecture or file layout. Can work in a small section of your page — doesn’t need to control whole page.
  • Where: GitHub and own site
  • When: In production for nearly 2 years now
  • Who: Alex MacCaw
  • What:
    • MVC in JavaScript, MIT license
    • Worked example originally written for an O’Reilly book grew into an actual OSS project
    • Is a kind of modified clone of Backbone (hence the name)
  • Why: You like Backbone, but want a few things to be different.
  • Where: GitHub and own site
  • When: It’s past v1.0.0 now
  • Who: the team at Shopify (an eCommerce platform company)
  • What:
    • MVC in JavaScript, almost exclusively for Rails+CoffeeScript developers, MIT licensed
    • Most opinionated of them all. You must follow their conventions (e.g., for file layout and URLs) or, as they say in their presentation,”go use another framework
    • Full-stack framework with pretty rich models, views, and controllers and routing. And observability mechanism of course.
    • DOM-based templating.
  • Why: If you use Rails and CoffeeScript, you’ll be right at home
  • Where: GitHub and own site
  • When: Currently at 0.9. Aiming for 1.0 in coming months.
  • Who: the team at Bitovi (a JavaScript consulting/training company)
  • What:
    • MVC in JavaScript, MIT licensed
    • REST-persistable models, basic routing, string-based templating
    • Not widely known (I hadn’t heard of it before last week), though is actually a reboot of the older JavaScriptMVC project
  • Why: Aims to be the best of all worlds by delivering features similar to the above libraries while also being small
  • Where: GitHub and own site
  • When: Past 1.0 already


If you’re trying to make sense of which of these is a good starting point for your project, I’d suggest two questions areas to consider:

  • Scope. How much do you want a framework or library to do for you? Are you starting from blank and want a complete pre-prepared architecture to guide you from beginning to end? Or do you prefer to pick your own combinations of patterns and libraries? Either choice has value and is right for different projects and teams.
  • Design aesthetic. Have you actually looked at code and tried building something small with each of your candidates? Do you like doing it? Don’t choose based on descriptions or feature lists alone: they’re relevant but limited. Ignoring your own subjective coding experience would be like picking a novel based on the number of chapters, or a spouse based on their resume/CV.

Despite the differences, I’d argue there is one killer feature all the above technologies share: the idea of Model/View separation. This is a classic design pattern that predates the web itself by about 20 years. If you’re building even the most basic kind of web application UI, you’ll almost certainly benefit from applying this on the client.