Multiple var statements in JavaScript, not superfluous

|

I’m not sure where or when it happened, but at some point the JavaScript community decided that multiple, individual var statements were superfluous, instead opting for a single, combined var statement with a comma-separated list of variable declarations and assignments whenever possible.

Just in case you don’t know what I mean, I’ll illustrate:

// Single, combined var statement.
var foo = 1,
    bar = 2;

// Multiple, individual var statements.
var foo = 1;
var bar = 2;

I’ve asked a number of talented JavaScript programmers why they prefer a single, combined var statement with multiple declarations and assignments to multiple, individual var statements, and the only responses I’ve been able to get seem entirely subjective:

  1. Multiple var statements are superfluous.
  2. Multiple var statements are noobish.
  3. Combined var statements look better.

While I can’t argue with the last point, in JavaScript, multiple var statements aren’t superfluous and they aren’t noobish. They reduce the effort it takes to maintain code.

Maintenance

Consider this scenario. We’ve got some code that needs to change. It turns out foo shouldn’t be hard-coded to 1, because it’s always going to be bar - 1. So, let’s update the offending code so that foo is set after bar.

// Before:
var foo = 1,
    bar = 2;

// After:
var bar = 2,
    foo = bar - 1;

The preceding code may look relatively innocuous, but in your editor of choice, actually try changing the above “before” code to the “after” version. Count how many separate actions are involved just to reorder the two assignments.

Now try performing those changes in the following version. Count the number of actions required, and note how much less work it is.

// Before:
var foo = 1;
var bar = 2;

// After
var bar = 2;
var foo = bar - 1;

ASI

How about Automatic Semicolon Insertion? Forgetting a comma separator in a var statement has a greater impact than forgetting a semicolon after a var statement. But of course, you lint your code, so this would never be an issue. Right?

var foo = 1,
    bar = 2  // Oops, ASI has just inserted a semicolon here...
    baz = 3; // ...and now the outer (global?) var `baz` has a value of 3.

// PROBLEM SOLVED!
var foo = 1;
var bar = 2  // No worries, ASI's got your back. Semicolon: added.
var baz = 3;

FWIW, I’m not a huge fan of ASI. I recently wrote an article, News Flash: Semicolons Required in JavaScript, that explains why. That being said, love it or hate it, ASI is a part of JavaScript.

Indentation

Of course, there’s always the tabs-vs-spaces argument. Which looks better when declaring multiple variables in a single var statement, tabs or spaces? The correct answer: neither. They both look horrible.

// While 4-space soft tabs look great...
var foo = 1,
    bar = 2;

// 2-space soft tabs look kinda gross.
var foo = 1,
  bar = 2;

// Tab indents look horrible unless your editor is set to display tabs 4
// chars wide. This is what tab-indented code looks like in browsers and
// in many editors:
var foo = 1,
        bar = 2;

// PROBLEM SOLVED! Indentation doesn't need to matter.
var foo = 1;
var bar = 2;

More indentation: Multi-line expressions

What about assigning multiple multi-line object / array literals or function expressions in a single var statement? How does that look? Pretty awesome, I bet.

// I might start out with one var...
var foo = {
    prop: 123
};

// But when I add another, if I don't re-indent the original var it's ugly:
var foo = {
    prop: 123
},
    bar = {
        prop: 456
    };

// Is the solution to not indent either of them? It is if you want your code
// to be impossible to read.
var foo = {
    prop: 123
},
bar = {
    prop: 456
};

// Ok, so the solution might be to re-indent foo, but that's just introducing
// unnecessary noise into your commits. Reformatting code that's otherwise
// unrelated to the changed code sucks. Whitespace commits? They suck too.
var foo = {
        prop: 123
    },
    bar = {
        prop: 456
    };

// PROBLEM SOLVED! Separate var statements: awesome.
var foo = {
    prop: 123
};
var bar = {
    prop: 456
};

Even more indentation: Comments

You don’t need to write a book every time you add a line of code, but it’s often helpful to write comments—especially for variables that are being declared at the top of a function, far away from where they’re actually being used.

// I'm going to comment foo here.
var foo = 1,
// And now I'm going to comment bar. Wait, should this comment be
// indented to line up with the code underneath it?
    bar = 2;

// Well, I'm still going to comment foo here.
var foo = 1,
    // Now the bar comment is indented. But now the comments don't align.
    bar = 2;

var // Ah, the perfect solution. I'll comment foo here.
        foo = 1,
        // And comment bar here. But with tabs, these might not align.
        bar = 2;

var // Ok, with 4-space indents, comments line up.
    foo = 1,
    // But how about we try to reorder these two variable assignments now.
    // Remember that example? Hahaha, good luck with that.
    bar = 2;

// PROBLEM SOLVED! We can just comment foo here.
var foo = 1;
// And comment bar here.
var bar = 2;

PS. programmers who said “combined var statements look better” (#3 in the above list), I’m guessing you use 4-space indents with no comments, because code like this can’t help but look insanely bad. Ok, I guess I’m arguing that point, after all.

Minification

It’s the new millenium. A good minifier, like UglifyJS, knows how to combine multiple sequential var statements into a single, comma separated var statement, so you no longer need to “prematurely optimize” for that use-case by combining your var statements.

If your minifier can’t do this, get a better minifier.

// Before minification:
var foo = 1;
var bar = 2;

// After minification:
var foo=1,bar=2;

In summary

I acknowledge that these are opinions. Just because I’ve given this an inordinate amount of thought doesn’t make me any more qualified to make recommendations than anyone else. Or does it?

My rule is as-follows: I’ll put multiple comma-separated declarations in a single var statement, but only if they don’t have assignments. Assignments must be in their own var statement. Like this:

// SIMPLE AND SEXY
var foo, bar, baz;
var abc = 1;
var def = 2;

Either way, I’d recommend that you give it some thought and figure out what you want to do. I personally don’t care what you do, as long as you can defend the choices you’ve made.

Postscript: Rick Waldron explained to me that he’s been using a similar style lately. While he uses a single var statement per execution context, he only uses it to declare variables. Assignments only happen as-needed in the function body. You know, just like JavaScript does it.

Post A Comment

  • Any of these HTML tags may be used for style: a, b, i, br, p, strong, em, pre, code.
  • Multi-line JavaScript code should be wrapped in <pre class="brush:js"></pre>
    (supported syntax highlighting brushes: js, css, php, plain, bash, ruby, html, xml)
  • Use &lt; instead of < and &gt; instead of > in the examples themselves.