Javascript: Elements of Style


I recently read Farhad Manjoo’s polemic on slate explaining that using two spaces after a full stop is flat out wrong. Of course things are never that simple and Manifest Destiny has an impassioned rebuttal.

Going back over what I’ve just written, I discover that I too am one of the hated double-spacers. Since I now know which camp I’m in, I can invent my reason for being in it: the full stop belongs to the dying sentence but two spaces indicate the intake of breath before I begin to express my next thought. It’s not merely a break in flow like the lowly single space, it’s the preparation for exhalation.

It’s interesting that language can excite such arguments even on topics that make no difference to meanings. Programming languages are no exception; every company I’ve worked in has had its own style guide or coding standard.

When I’m pair programming with a prospective candidate, I don’t care too much which style they use but it’s important they use one. Someone who leaves copy and pasted code indented incorrectly or who places keywords like the paint on a Jackson Pollack painting is someone who doesn’t realise that their most important readers are not compilers and interpreters but other programmers. They’re also the kind of people who will leave archaeological jsdoc around long after its stone age code has been replaced with steel and glass. Just as authors take pride not only in the conceptual – what they make their readers think – but also in how their work looks on the page, so must programmers.

Once within a company however, more important than any single aesthetic rule within the coding standard is the benefit of the consistency it brings to the entire codebase. That they understand this is the reason that good coders will follow even rules they personally hate.

Nevertheless, we don’t want the rules to become so overwhelming that people feel stifled in what they write. One of the worst pieces of code I ever saw went something like this:

function fred() {
	var result = 0;
	do {
		if (complicatedCondition) {
			if (someOtherCondition) {
				result = 12;
				break;
			}
		}
		/* … more similar code … */
	} while (false);
	return result;
}

It was written by someone who was trying to follow the rule that code is simpler if it only has one return statement at the end of the function and his way of doing that was to refashion the goto out of a do… while (false) loop, and a bunch of breaks. It reminds me of someone who having learnt to use commas tries to use them to force their own mental spacing onto everyone else.

So the question is this: how can we choose style rules that will give us benefits, but not drive our programmers to insanity?

Here are my suggestions in order of precedence:

  1. Style rules that make us less likely to introduce bugs into the code.
  2. Style rules that make code look nice.
  3. Style rules that make code more concise.

Despite the amount of aesthetic judgement in these matters, it can be interesting how much people tend to agree. The Google style guide for JavaScript is not vastly dissimilar from our own here at Caplin.

One of the areas in the google style guide that does breaks my rule 0 however, is the section at the end that encourages coders to use the truthiness rules of javascript to make various checks easier.

In particular where you say if (expression) {/*truthy path*/} else {/*nontruthy path*/}

Now in java if you do this the expression gets considered as a boolean and that will determine which path you take. No mystery. In javascript which path will be taken is very little to do with whether expression == true. This page discusses some of the rules but few javascript coders know them all well.

I had this debate recently with a skilled coder, whose position was that it usually does what you expect so it’s perfectly fine to use it to check if an object is defined, rather than follow a suggested style rule to always explitically compare (e.g. against null). Two weeks later, I was helping someone else debug that same code and found an unexpected boolean false was causing the nontruthy path to execute even when the value was defined. Although the original coder had understood the truthiness rules, he’d not expected the value being checked to ever contain a boolean false (the same problem would have happened with an empty string, a NaN or a 0).

This is the central point – it doesn’t matter which looks nicer when a simple style rule can ensure subtle and hard to find errors simply never make it into the code.

The Serial (or Harvard, or Oxford) Comma is an example of the same principle from English. Conventional usage doesn’t place a comma before an ‘and’ when writing a list, however this can lead to ambiguities. The classic example is the book dedication “To my parents, Ayn Rand and God”. Even if you hate the extra comma, when it comes to questions of parentage it’s better to grit your teeth and write what will not be misunderstood.

Related Posts with Thumbnails

3 Comments

  • Testing something for equality with true, especially using ==, is a very bad idea. The first, second, third, and last rule of JavaScript style is never to use == or !=. They do not do what you expect. In fact, == is not even transitive.

    • Adam Iley says:

      I agree, I hope that nobody read this article as encouraging people to use ==. I personally use it only in one place; when checking against null and undefined, I do an x == null check. In every other case, === is to be preferred.

      Something to be careful of though is that if (x) also behaves differently to what many developers expect, e.g. when x is 0, the empty string, a boolean false, NaN… It’s usually better to make your intended check explicit e.g. with if (x === true) or if (x !== null)

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image