Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A better coding convention for lists and object literals in JavaScript
// See comments below.
// This code sample and justification brought to you by
// Isaac Z. Schlueter, aka isaacs
// standard style
var a = "ape",
b = "bat",
c = "cat",
d = "dog",
e = "elf",
f = "fly",
g = "gnu",
h = "hat",
i = "ibu";
// comma-first style
var a = "ape"
, b = "bat"
, c = "cat"
, d = "dog"
, e = "elf"
, f = "fly"
, g = "gnu"
, h = "hat"
, i = "ibu"
;
// error in standard style
var a = "ape",
b = "bat",
c = "cat",
d = "dog"
e = "elf",
f = "fly",
g = "gnu",
h = "hat",
i = "ibu";
// error in comma-first style
var a = "ape"
, b = "bat"
, c = "cat"
, d = "dog"
e = "elf"
, f = "fly"
, g = "gnu"
, h = "hat"
, i = "ibu"
;
// Objects:
// JSON.stringify style
var o = {
a : "ape",
b : "bat",
c : "cat",
d : "dog",
e : "elf",
f : "fly",
g : "gnu",
h : "hat",
i : "ibu"
},
a = [
[ "ape", "bat" ],
[ "cat", "dog" ],
[ "elf", "fly" ],
[ "gnu", "hat" ],
[ "ibu" ]
];
// comma-first
var o =
{ a : "ape"
, b : "bat"
, c : "cat"
, d : "dog"
, e : "elf"
, f : "fly"
, g : "gnu"
, h : "hat"
, i : "ibu"
}
, a =
[ [ "ape", "bat" ]
, [ "cat", "dog" ]
, [ "elf", "fly" ]
, [ "gnu", "hat" ]
, [ "ibu" ]
];
// errors in objects:
// JSON.stringify style
var o = {
a : "ape",
b : "bat",
c : "cat",
d : "dog"
e : "elf",
f : "fly",
g : "gnu",
h : "hat",
i : "ibu"
},
a = [
[ "ape", "bat" ],
[ "cat", "dog" ],
[ "elf", "fly" ]
[ "gnu", "hat" ],
[ "ibu" ]
];
// comma-first
var o =
{ a : "ape"
, b : "bat"
, c : "cat"
, d : "dog"
e : "elf"
, f : "fly"
, g : "gnu"
, h : "hat"
, i : "ibu"
}
, a =
[ [ "ape", "bat" ]
, [ "cat", "dog" ]
, [ "elf", "fly" ]
[ "gnu", "hat" ]
, [ "ibu" ]
];
// Addendum: effects on the return statement.
// It does not break.
return [ 1
, 2
, 3
] // returns [1,2,3]
return { a : "ape"
, b : "bat"
} // returns {a:"ape",b:"bat"}
// even just separating two values by commas is fine,
// though a bit silly
return 1
, 2
, 3
, 4 // returns the last value, 4
// this, however is wrong:
return
1
, 2 // returns undefined, because of semicolon-insertion.
// so is this. otb == fail.
return
{ a : "ape"
, b : "bat"
} // returns undefined,
// then creates a block with two named statements.
// this is ok:
return ( 1
, 2
) // returns 2
// so is this:
return (
{ a : "ape"
, b : "bat"
}
) // returns {a:"ape",b:"bat"}
// Addendum 2: A function call
doSomething( aPrettyLongVariableName
, "A string, which has some useful information"
, "If you put these all together, it'd be too long"
, { a: "is for antelope", b: "is for bat" }
, 42
)
// Addendum 3: More realistic error in standard style:
// leaks FIVE globals!
var a = "ape eat banana",
b = "bat, allowed to fly",
c = "cat toy",
d = "dog chasing the mailman,"
e = "elf lord",
f = "fly through the air",
g = "gnu is not unix",
h = "hat goes on your head",
i = "ibu isn't a cow";
// Error: Can't call method 'forEach' of undefined.
// not passing in undefined as an argument!??
mergeLists([ apple, [ penelope, granger ] ],
[ fun ],
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
[ "mary's store has many pies, and cookies, and eggs," ]
[ function() { doSomething() } ]);
@meisl
Copy link

meisl commented Oct 28, 2013

Adding on @Spudz76's previous comment, I just recently found myself doing this:

var exampleArray = [ undefined
    , 7
    , 5
    , 1
    , 4
].splice(1);
letsSeeHowElementOrderMatters(exampleArray);

Looks rather crazy but serves me really well when having to change the order of elements often (eg for experimenting*). Works particularly nicely if your editor let's you select a whole line by just one click (eg the line nr) and then move it by dragging.

Btw: got nothing alike for object literals - BUT: ... well, think about it ...!


[] in that particular instance I was hunting down a serious perf degradation that varied heavily with the actual order of elements. In the end it turned out to be a proper bug. Once this bug was fixed, the order didn't matter anymore wrt to perf. However, *up until I was able to spot and fix this bug I did change the order of elems a lot and the resulting changes in the profile actually gave me the idea of what was really going on. Of course, it weren't just nrs as in the example, rather complex interdependent objects.

@gabrieldodan
Copy link

gabrieldodan commented Feb 7, 2014

Personally I see no benefit on comma first style, the lines looks like are comment lines, like VBScript comment lines. Literal objects with 2+ levels are very unreadable. By the why, comma first supporters, why don't use also semicolon in front of statement ? :) e.g.

fucntion1()
;function2()
;function3()

@waynebloss
Copy link

waynebloss commented Apr 9, 2014

Whoever said "use better tools" was right. (And there is a wrong here.) Comma-first style seems analogous to burning down your barn to get rid of some rats. Don't do that! Just get some rat traps.

Of course you're welcome to "optimize for [your] human brain", but don't think that you're optimizing it for other people's brains (or even the majority). If you just use tools to catch these mistakes, you can avoid the whole issue.

This guy is right too - you want punctuation to disappear when you're reading code - http://blog.outsharked.com/2012/05/on-javascript-style.html

@f3z0
Copy link

f3z0 commented Apr 12, 2014

I'm actually a fan of comma first because of the arguments presented above but it indirectly violates google style guidelines.

@gaastonsr
Copy link

gaastonsr commented Feb 12, 2015

@waynebloss thanks for that link. Interesting read.

@rafanake
Copy link

rafanake commented Mar 2, 2015

If you use it first, youre VERY wrong
Dont do it plz.

@chiefGui
Copy link

chiefGui commented Apr 10, 2015

@f3z0 Is Google an axiom?
@rafanake Why?

@kinsho
Copy link

kinsho commented Apr 27, 2015

While I understand the comma-first approach may make JSON-related errors easier to catch, it is by far the ugliest coding convention I have seen in my limited programming career. A good editor usually catches errors related to missing commas in JSON files anyway. I truly see little value in this.

@smaudet
Copy link

smaudet commented Jul 3, 2015

It actually looks much nicer to me this way:

  1. Var statements line up much more nicely
  2. Added benefit of catching errors
  3. You can insert/remove single lines

I always found the comma at the end the most moronic, especially if you append to arrays instead of just inserting at the beginning all the time. You have to add a comma to the previous line, which is inconvenient at best, and problematic at worst.

With the comma before approach, you only have to deal with this issue once (making sure your first definition lines up), and then you're done.

The only disadvantage I see is that there are a lot of formats doing this the old, broken way of 'comma after', including, incidentally, JSON.stringify. Which is why I found this debate at all.

@TheNotary
Copy link

TheNotary commented Aug 5, 2015

Hmm... 'use strict' prevents leaking to global. When I add to var blocks (which I use infrequently as a means of being articulate), I do so to the middle more so than I do to the beginning and end. But if I encountered this code from someone else, I don't think I'd have a 'conventional problem' with understanding it. It looks like a config file that uses commas in a somewhat non-english manor. I don't think I'd like to implement commas in this way though.

@matthew-dean
Copy link

matthew-dean commented Oct 1, 2015

Yay! Another pointless code debate.

@Potherca
Copy link

Potherca commented Nov 29, 2015

I can't believe people are seriously debating this and trying to use "arguments" on this topic. It makes about as much sense to debate if a painter should hold a brush in their left or right hand.

It doesn't matter

To left-handed people one answer seems more fitting while right-handed people will opt for the opposite for exactly the same reason.

Just like tabs vs. spaces, brace placement and first vs. third person narration it all boils down to personal preference.

@isaacs made an effort to explain why this particular style works for him. Well done.
Anyone who considers the title "A better coding convention ..." anything other than click-bait has a lot of growing up to do.

Really... Can we all just go back to debating which Doctor Who is better?

@eladkarako
Copy link

eladkarako commented Jan 30, 2016

Tip: Beautify && Comma first, Almost No Code!

var obj = {url:"http://example.com",number:1,complex:["first",{second:"null"}]}
  • Beautify, comma-last
    JSON.stringify(obj, null, 2)
    {
      "url": "http://example.com",
      "number": 1,
      "complex": [
        "first",
        {
          "second": "null"
        }
      ]
    }
  • Beautify, comma-first - column start ("Greek style")
    JSON.stringify(obj, null, 2).replace(/,\n /g, "\n ,")
    {
      "url": "http://example.com"
     , "number": 1
     , "objects": [
        "first"
     ,   {
          "second": "null"
        }
      ]
    }
  • Beautify, comma-first - word start ("English style") - Preferred.
    JSON.stringify(obj, null, 2).replace(/,\n /g, "\n ,").replace(/ *(,(\ +))/g,"$2,")
    {
      "url": "http://example.com"
     ,"number": 1
     ,"objects": [
        "first"
       ,{
          "second": "null"
        }
      ]
    }

#Source

@QuentinUK
Copy link

QuentinUK commented Mar 30, 2016

Yoda commas.

@NoelBaron
Copy link

NoelBaron commented Aug 12, 2016

For nearly 16 years of our lives, we write essay after essay using commas. On top of that, we write billions of emails. With all the variables and preferences in our shared environments, shouldn't we at least adhere to our life-long habit of left-to-right comma interpretation?

In my humble opinion, I prefer reading code that isn't totally opposite our natural tendencies.

This doesn't feel natural at all, although technically it is the same text:

For nearly 16 years of our lives
, we write essay after essay using commas. On top of that
, we write billions of emails. With all the variables and preferences in our shared environments
, shouldn't we at least adhere to our life-long habit of left-to-right comma interpretation?

@eladkarako
Copy link

eladkarako commented Oct 25, 2016

@NoelBaron, linguistically, a compound-sentence has a comma so you'll pretty much know when to halt for a breather, but on your sample text, inserting a line-break before the comma (creating a comma-first look) also implies a full-stop or a new paragraph, comma on code has no linguistics value, and one should not be looking for such. On inventing a new program-language, we might as well use pipeline, hash-tag or any other characters to separate code-blocks, which do not have analogous meaning in English language-composition thus, not creating this confusion.

Most of pro-comma-first developers usually mention their lack of forgotten commas at the end of a long line of code, or even the OCD relief of same-column-straightening of characters ;)

Anyway, the comma-first convention is gaining quite a lot of popularity among users lately,
I can say that software-developers at Google (Israel) are using it on most of the new projects, due to its superb readability.

@Inateno
Copy link

Inateno commented Nov 21, 2016

I give a star here since I discovered this place lol.

I'm using commas-first style almost since I started JS around 6 years ago now.

Guys you also missed something, commas-first is essential when you use multilines keyboard shortcut.

In VS or Sublime, CTRL + D for few entry in a JSON then END then add somehting, paste, or select a value. You don't have to deal wth the comma at the end.
Also CTRL + SHIT + TOP or DOWN in VS will make a multi-line cursor, then SHIFT + END and you selected all values excepted commas (or just select the keys, or the values, whatever).

I use this everyday everytime and each times I show this to a developer that is not using these shortcuts (and not using commas-first) he reconsider his position lol.

@fischerflorian
Copy link

fischerflorian commented Mar 28, 2017

As a general rule, you should split your statement at the highest place possible in your syntax tree. Usually at an operator.
Since that operator is the pivot between 2 lines, it should be put prominently at the begin of the line.
Therefore the comma, or any other operator, +, &&, should start the line.

@adius
Copy link

adius commented May 12, 2017

Use ternjs / eslint and get a life.
Putting the least important characters of the code up front is ridiculous.

@osher
Copy link

osher commented Dec 27, 2017

actually, I love it and have been using it for years.
the comma on the left just looks like a bullet list.
ever since I stared using it - I never forgot a comma or struggled with braces again, even when working with nano on remote files.

but - I'm working with a team now that will agree to this style only if it will be supported by the lindter.
so - is there an eslint rule I can use to enforce this style, especially for arrays and objects?

@alanosman
Copy link

alanosman commented Feb 5, 2018

Is there an eslint rule that will not choke when you do something like this? My eslint configuration complains about Project being indented by 2 chars.

const {
      Project
    , Dimension
    , Task
    , View
    , Layout
    , User
    , Group
    , Organization
    , CustomField
} = db.model;

@sophana
Copy link

sophana commented Dec 1, 2018

It's too bad so few people use comma (and operator) first.
There are so many bad examples here.
Comma and operator first is really useful when you nest complex data structures or code.
Here is a case where it is good at:

x = {
    a : ( b + 27 * (
        foo1(
            b
        +   (   (c + 232312)
            *   (   foo2(
                        (d + 3423423 * foo34(34))
                    *   (y+3243)
                    )
                +   foo3(
                        (234 * sdf + 23 * dfdse )
                    ,   23423 + foo45(23)
                    )
                )
            *   ( 23423 / 34)
            )
        +   (   234234 / sdf + 23423)
        +   (   foo4(234234)
            /   foo5(
                    foo34(
                        (   (   fo345(3434 + 2323423)
                            +   23423
                            )
                        /   234
                        )
                    ,   [ 23234, 23432, 234234]
                    )
                /   349
                )
            )
        )
    ))
,   b : 234
,   c : [
        34534
    ,   534634
    ,   98
    ]
,   d : {
        x1 : [
            23423
        ,   232
        ,   43+343*(
                343
            +   324
            )
        ,   23
        ]
    ,   x2: 234
    ,   x3: foo(2323 + (
                ( foo56(234) + 3434)
            /   (2342 + foo6(2323))
            ))
    ,   x4: 34534
    }
}

@Mcfloy
Copy link

Mcfloy commented Apr 9, 2019

I don't know how I got there, probably about the trailing comma debate I had with a colleague, but honestly this hurts my eyes so much. You don't do comma-first because firstly it's ugly and unintuitive. Javascript was designed like any coding language to be human-friendly. The creators knew how to read and write english, meaning that you should respect the comma position as you would in an non programming language.

Now if you write like this ,you'll see that this is by far the dumbest way to say "Hey I'm a hipster I write code with comma first" ,that's not how you're supposed to do things and you'll be the only one to do this in a team that would dare to hire you.

Comma is not a operator so I don't see the point how saying it should be the first thing in a line and in english (or any other language), a comma is attached to the previous word and a space (or a new line) must be put after this comma.

I really think I'm in the flat earth conference.

@bhubr
Copy link

bhubr commented May 18, 2019

@Mcfloy I feel you!

I cringe every time I see this comma-first garbage. And I think I have the best reason not to use comma-first: I used to work in a team where one developer, working alone on a project, had put them all around.

The guy was fired (for other reasons, the main one being that he had done a poor job). I was hired to replace him, and was then joined by two other developers. Every dev in the company, including others not working on this project - that is 15 persons roughly - kind of screamed in horror when I showed them the codebase we had inherited.

So if you want a single reason why not to use this crap, here it is: no one in his right mind does it, and no one wants to hear your explanation about why it's so brilliant, because it's just an insult to their eyes. If you do use it, you'll be looked upon by your teammates as being an insufferable know-it-all who thinks he's just invented hot water.

Thank God, common ESLint rules have banished this creature of doom from our world (hopefully).

@alystair
Copy link

alystair commented Apr 5, 2020

Not a chance @bhubr, some of us like our "comma-style":[2,"first"] rule ;)

The only place I've seen it cause issues is with JSDOC blocks not being identified correctly by the IDE.

A lot of the examples in this thread are using variables values of same/same character lengths. When line length is random it becomes much more obvious that comma-first adds value.

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