23

Tell me please, what is the sacred power of the style below:

var javascript = new Language(
  'Brendan Eich'
, new Date(1995, 0, 1)
, ['C', 'Java', 'Scheme']
);

Why do lots of programmers use that style? What benefits does it have? For example,

var javascript = new Language(
  'Brendan Eich',
  new Date(1995, 0, 1),
  ['C', 'Java', 'Scheme']
);

I like much more than previous. Thanks.

3
  • 4
    Questions like this are probably more appropriate for programmers.stackexchange.com
    – rooftop
    May 7, 2012 at 14:51
  • 1
    Pretty sure comma at end of line is better in js because of semicolon insertion. Jun 3, 2013 at 8:13
  • 1
    I call ASI "Asinine Semicolon Insertion"
    – doug65536
    Jan 3, 2017 at 9:01

9 Answers 9

16

Lots of great answers already. Allow me to give you my own one, to make things as clear as possible.

I personally call this way of writing code 'Haskel style', since it's a common style to use in Haskell. Let me give you a Haskell example first:

data Settings = -- The user settings
    { has_sound     :: Bool   -- Determines if the user has sound
    , has_power     :: Bool   -- Determines if the user has electricity
    , has_graphics  :: Bool   -- Determines if the user has graphics
    , user_name     :: String -- The name of the user
    , user_password :: String -- The hashed password of the user
    , user_email    :: Email  -- The email address of the user
    , stylesheet    :: Style  -- The stylesheet to use
    }

And a Javascript snippet from one of my projects:

var events // Holds the events to generate a event handler for.
  , var2   // Quick description for var2.
  , var3   // Quick description for var3.
  , ...    // ...
  ;
events = // Event handlers will be generated for the following events:
    [ "onmousedown"  // Works outside of the window element
    , "onmouseup"    // Works outside of the window element
    , "onmousemove"  // Works outside of the window element
    , "onmousewheel" // This will handle DOMMouseScroll aswell
    ];

Benefits of 'Haskell style'

Easy to read

'Haskell style' takes advantage of the column style layout. This column style makes your code more readable. In fact, it makes your code so much more readable that you use it all the time. Imagine writing code without tabs or leading spaces!

By taking advantage of column style layout, variable names, types, etc. are easier to read aswell. By grouping up variables by prefix, our future reader will easily find what he is looking for, without using a advanced search query.

Easy to document

Column style layout has more advantages. By grouping up our code we can add a column reserved for comments. Now you can read your code without even needing color highlighting, and adding information to your comment is as easy as finding the right column and modifying it. Besides, this column-like style of documenting your code is pretty much what you get after using a documentation generator like Doxygen, removing the necessity for this kind of tool.

Easy to notice mistakes

Noticing a missing comma is a piece of cake using this style of coding. Simply look for a line that doesn't start with it! On the other side of the spectrum, we have the comma's at the end of the line. We missed one? Nope, because it is the last element, or because the expression continues on the next line. And finding the first element in a list is as easy as could be. When dealing with long lines, the first element is easily overlooked, but by placing the first element on it's own line and puting a [ or { instead of a , right in front of it, it's easy to spot.

Easily scalable

You might say "But this layout style will get imposible to handle once the expression gets big!", which is quite true, but is this any different for the rest of your code? I think that by using column style you will at least keep your code readable, which in the long run is worth more than the struggle you might have to fit it into a column layout.

All in one example!

var scalable = // This is a example variable
    [
        [ new MyObject // This is how I would style Object Allocation
              ( "11"
              , "This is the first element"
              , function // This is a very secret function...
                  ( secret   // ..with secret..
                  , variable // ..variable..
                  , names    // ..names!
                  )
                {
                    // <-- Use spaces, not tabs :)
                }
              )
        , "12"
        ]
    ,
        [ { id:   21                          // Where's 20?
          , name: "This is the third element" // It sure is
          , func: function() { /* My body feels empty :c */ }
          }
        , "22" // Notice how 21 is a integer, not a string. Sneaky!
        ]
    ];

TL; DR

This style of placing comma's, 'Haskell style', has a couple of advantages:

  • Easy to read
  • Easy to document
  • Easy to notice mistakes
  • Easily scalable
2
  • 6
    You can use column spacing without leading commas, making leading or trailing equally easy to document/comment. And I would disagree with the "easier to read", no matter how many Haskellers say that, because it requires having "noise" before the first thing of value on the line, meaning you need to train your brain to 'hide' the noise when scanning through code, and your brain will always need to process it... The "missing comma at the end" is such a trivial thing to spot and fix that the cleanliness & greater ease of scanning seems worth it.
    – kevlarr
    Aug 23, 2017 at 13:45
  • 8
    those commas look like cigarette butts on the ground Oct 11, 2018 at 12:33
12

If you have an extra comma in the end of the last line it will work in some browsers but not in all browsers. Making the error harder to detect than a extra comma at the beginning (which fails on all browsers). And most developers prefer to see the error right away (so they can fix it), instead of risking a production issue for inadvertently not supporting some browsers. Especially if the solution is as easy as removing a comma.

Plus, having the comma at the beginning of the line, make it simpler to add a line at the end and you will have to touch only that line (you will not need to add the comma in the line before). Which is important if you are using version control (e.g. diff, annotate, bisect). Someone can argue that adding a line at beginning of the array or object will need the same extra work of touching 2 lines (if you use commas at the beginning), but in my experience, inserting a line at the beginning is much less likely that inserting a line at the end.

5
  • 13
    And if you have an extra comma at the beginning of the first line, it will fail in pretty much all browsers. Just saying.
    – cHao
    May 7, 2012 at 14:35
  • I agree with this point of view. But it also strange when people use that rule inside of var section. In this case we should remove semicolon each line we want to add variable, or use ASI which is not good, IMHO. May 7, 2012 at 17:31
  • 1
    @cHao sure, but I prefer the bug on the first line which is easy to detect in any browser and should be discovered in the testing made by the developer, to the bug in the last line which can be hidden for some time and be discovered in production when is more expensive to fix. May 7, 2012 at 19:42
  • 1
    This might be old, but I doubt everyone will agree that inserting a line in the beginning is "much less likely". Personally I would think inserting a line at the beginning of a list is just as likely as at the end, or the middle, or at any other point. It kind of depends on what's in the list, doesn't it? Even for function signatures spanning multiple lines when necessary (eww), I've inserted arguments at the beginning as often as at the end, depending on which makes more sense semantically.
    – kevlarr
    Aug 23, 2017 at 13:38
  • @kevlarr fair enough. I've edited my answer. Thank you for your feedback. Oct 19, 2017 at 22:16
11

This is because the comma belong to the new line next statement and not the previous one. (As @Dave Newton states it in his comment below: the pseudo-BNF would be foo [, foo]*-ish)

For example:

If you have this:

a,
b,
c

If you need to remove the c then you need to delete two things: de c and the comma on the previous line. If you do this:

a
,b
,c

now you only need to delete the ,c line. It makes more sense this way, because the comma behind the b in the first example only is needed because of the c. It does look worse this way though. It's a trade off between maintainability of your code and the way it looks.

7
  • 2
    any argument besides your personal opinion?
    – mata
    May 7, 2012 at 14:16
  • 1
    I explained it a little more. I hope it helps May 7, 2012 at 14:18
  • 2
    @mata Syntatically, the pseudo-BNF would be foo [, foo]*-ish. I think the argument would be that the comma is associated with the following statements, not the initial one. This doesn't address the "new line" thing, but IMO commas are more-tightly associated with following foos. May 7, 2012 at 14:18
  • 28
    @koenp: Now, you have a problem if you delete the a line. (You need to delete not just that line, but the comma following it.) You haven't decreased the number of problems, just shuffled them around.
    – cHao
    May 7, 2012 at 14:24
  • it wasn't about not understanding the point, it was about the original answer being "because. thats how it is." (sort of). however it's better now (however debatable it may be).
    – mata
    May 7, 2012 at 14:27
9

I think it's done so that it's easier to spot a missed comma.

var something = 0,
    foo = "a string",
    somethingElse = []
    bar;

var something = 0
  , foo = "a string"
    somethingElse = []
  , bar;
0
3

It is easier to just look at your code to verify you have a comma where needed. If you had to scan the end of each line of code the missing commas wouldn't just jump out like they do when they are lined up on the left hand side.

2
  • So you increase maintainability at the cost of readability...? Doesn't seem like you're really gaining anything here.
    – cHao
    May 7, 2012 at 14:21
  • I think, if we have line longer than 80 symbols - something is wrong :) and It's not a point to decrease readability. But your point of view is interesting. Thanks! May 7, 2012 at 17:23
2

This offers a little bit of protection in languages which don't accept trailing commas from accidentally introducing syntax errors with trailing commas

In SQL, trailing commas will cause syntax errors. In JavaScript, it will be accepted most places, but will fail with a cryptic error in some Internet Explorer versions, for example.

JS works in most browsers, but fails in some

var thing = {
 a: 1,
 b: 2,
 // trailing comma
 c: 3,
};

Syntax error in SQL

SELECT
  col1,
  col2,
  -- Syntax error in SQL
  col3,
FROM table
5
  • It's .js, not SQL. and also tools like jslint/jshint also exist... And they show extra commas. May 7, 2012 at 17:26
  • @InviS Yes those tools do exist. Not everyone uses them. In fact, quite a lot of people do not use them. People who tend to adopt the comma-before style tend to do so across many languages, which is why I point out SQL. May 7, 2012 at 17:29
  • :) maybe, but I've seen that style only inside of example written by js experts :) Also, that style is often used inside of npm-packages on nodejs. May 7, 2012 at 17:36
  • @InviS What does it matter, expert or not? It is a coding standard which is often agreed upon by members of a team or project. It's entirely arbitrary. May 7, 2012 at 17:39
  • styles and use cases is a part of that. I think that new-by cant have perfect style of code-writing, but expert can. May 7, 2012 at 17:41
1

It's one way to make sure you don't forget the comma when adding a new item to a collection, and don't accidentally leave on a trailing comma in collections.

By putting it on the new line it's visually obvious.

I don't care for it, but I understand why people would.

1
  • It's simple when you're using ASI as I pointed above... May 7, 2012 at 17:34
0

You might be looking at generated code, for instance, when writing a loop to generate an SQL select statement sometimes I will write it like:

sql =  "SELECT";
sql += "  table.id"; // or some field that will always be in the query
for (var i = 0; i < 10; i++;) {
  sql += ",  table.field" + i; 
}
sql += "FROM table" // etc

Instead of adding the comma at the end and then having a condition to omit it on the last iteration of the loop or doing:

sql =  "SELECT";
for (var i = 0; i < 10; i++;) {
  sql += "  table.field" + i + ","; 
}
sql += "  table.id";
sql += "FROM table" // etc

Which is functionally equivalent, but then the ID doesn't appear where I usually want it.

1
  • nope, It was an example from some article about JS. May 7, 2012 at 17:34
-1

Maybe because removing or adding line and its commas is simpler with second example

Not the answer you're looking for? Browse other questions tagged or ask your own question.