JavaScript Comma Delimiter Pattern

Perhaps the most common syntactic error I find myself correcting in JavaScript is that of a simple missing comma separator on new lines. Such marginal oversights can become quite a nuisance to correct time and time again. Fortunately, there is a rather simple pattern which can be used to help avoid these errors with very little effort – only requiring code to be rewritten in a manner that reads more naturally while also being syntactically correct.

Typical missing comma scenario

If we are to consider the most common scenario where a comma is unintentionally omitted (and a subsequent exception is thrown), it can most likely be found within The Single var Pattern (irrespective of any personal preference towards or against the pattern itself).

For example, consider a typical block of code implementing a single var:

The above example, being rather typical and admittedly simple, does not pose much of a maintenance issue itself. However, if one is to refactor these declarations into a different order, add additional declarations, or specify more complex assignments, the probability of a comma being omitted unintentionally or becoming out of place increases.

In addition to The Single var Pattern, object literals are also a good source of occasional commas being omitted unintentionally, especially when nested within additional literals:

A Simple Solution

To help avoid such mistakes altogether, we can simply place commas before declarations, rather than after. At first, this may feel a bit awkward, but in time it becomes quite easy to get used to.

With this in mind, by placing commas first, the above could easily be refactored to the following:

As can be seen in the above example, considering we generally read code left to right, it becomes immediately apparent if a comma is missing.

For instance, take note of which implementation is easier to notice the missing comma:

I suspect most would agree that commas placed before stand out much more, and therefore it becomes much more apparent when one is missing. This appears to be so as the difference between the two is such that with commas placed after one needs to look for what is missing, whereas with commas placed before one sees what is missing.

As humans, our tendency towards patterns in general, and visual patterns in particular can not be understated. As developers, considering patterns are a significant part of our work, we should strive to take advantage of the most natural ones especially, even for things as seemingly marginal as placing comma separators first.

{ 2 comments to read ... please submit one more! }

  1. Great post. Kaizen at work.

{ 0 Pingbacks/Trackbacks }