Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active September 7, 2016 16:23
Show Gist options
  • Save nathansmith/b3d6a7eb001ff98fde5d to your computer and use it in GitHub Desktop.
Save nathansmith/b3d6a7eb001ff98fde5d to your computer and use it in GitHub Desktop.
Why I dislike chains of comma-separated variables.
//==================
// VARIABLES: START.
//==================
var foo = 'foo',
/*
Some lengthy explanation about `bar`
and what it does, why we care, etc.
*/
bar = 'bar',
/*
Some complex stuff here, so we need to
have a function that does some logic.
*/
baz = (function() {
'use strict';
var x = 1;
if (/* condition */) {
x = 2;
}
else if (/* condition */) {
x = 3;
}
else if (/* condition */) {
x = 4;
}
return x;
})(),
// More variables...
uno = 1,
dos = 2;
//================
// VARIABLES: END.
//================
@nathansmith
Copy link
Author

This is why I think comma separated variable declaration is bad. It gets hard to read.

I much prefer a var for each variable declaration, and letting a JS minifier handle the optimization.


More reading…

https://speakerdeck.com/nathansmith/red-dirt-js?slide=98

https://speakerdeck.com/nathansmith/red-dirt-js?slide=99

@chiefy
Copy link

chiefy commented Aug 1, 2014

What about

var foo, bar, baz, uno, dos;

foo = 'foo';
bar = 'bar';
....

@nathansmith
Copy link
Author

That works. But, becomes sort of a maintenance headache — "scroll to the top of the page (or function scope) to make a new var — scroll back down to where I was, and resume typing.

I'm aware of how variable hoisting works, and I feel like if/once you are, it's not that big of a deal.

Plus, JS minifiers that optimize code will change all the var foo, bar, baz… into a chain like that, for you.

I say put that burden on automation, not humans.

:)


For what it's worth, the Node.js code style guide specifies using one var per variable…

https://github.com/felixge/node-style-guide#declare-one-variable-per-var-statement

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment