Here’s a slice of code. What does it signify?
Well, you know it’s a set of variables, because you know that’s what I’m writing about today. It’s not exactly obvious otherwise, though. At a glance, am I looking at variables or the fields of an object? In very large files it’s tough to say. And are these declared with
const? This difference matters in ES6.
This style can also bury errors – the code above will leak global variables because I missed out a comma before the
resolver. Subtle bugs are evil bugs.
Most debuggers will treat code like
var x = a, y = b, ... = z; as a single line, and won’t allow the developer to step over each individual assignment. This behaviour has changed in Chrome recently, but many other devtools environments will still treat the var operation as a single step.
One nice thing about free vars is that we can create them at the exact moment they are needed:
This makes them a little easier to name. It also makes it easy to delete variables as soon as they’re no longer needed – otherwise unused variables inevitably find their way through refactoring, hiding in the middle of a huge var statement at the top of the file.
Especially when using
const. Do we indent successive vars using a single tab (easy to type, but looks ugly), or do we manually align each var with spaces?
And if we align the symbols, what happens when we mix
However you format it, the whitespace remains ragged and inconsistent. And these aesthetics matter, because ugly code is a distraction that harms readability.
Every time I add a variable to a function, I have to chop and change the position of a semicolon. PRs look more noisy than they need to be:
It sounds trivial, but in large organizations where the PRs come thick, fast, and very often span several files, it’s noise and content that gets in the way of quickly and efficiently greenlighting changes.
The single-var rule was popularised by Douglas Crockford, who believed it was necessary to protect developers from the curious scoping behaviour of
For instance, in the following loop, the iterator
i exists and can be read outside the loop. This often surprises a developer coming from another language:
That wouldn’t work in C++, for instance:
And that’s great. But we don’t live in the 90s any more. I wish we did – the music was better and in the UK you could actually buy houses – but the world has changed. Grunge is over. Side partings are no longer cool. Your beloved tamogochi is probably buried in the Great Garbage Patch of the Pacific Ocean. Most importantly, though, we now have ES6 and its
const keywords, both of which have ‘block scoping’ (like C) as opposed to the ‘function scoping’ of
So put the single var style to rest, friend, and type the extra keywords. It might look odd if you’re not used to it, but I guarantee that within a week you’ll never understood how you ever wrote otherwise.