Javascript Faux Pas

When transcribing thought to code, one should not break this set of coding etiquette.

Etiquette 1: Use less commas
When you finish speaking a sentence, there should be a sense of finale. Don’t end it in a high note like a question. Don’t end it with an “and” followed by a long pause and…

For code, when constructing a comma-separated set of items, make sure the last item does not end in a comma. A comma indicates there’s more to follow, but if there isn’t, don’t put it there.
$.ajax({
  url: ...,
  type: ...,
  success: function() {
    ...
  },
  statusCode: {
    500: function() {
      ...
    },
  },
});
Did you catch the error?
That’s right. Right after the statusCode {}, there’s an unnecessary comma.
Did you catch the 2nd error?
Right after the 500 within the statusCode, there’s another unnecessary comma.

While modern browsers will happily eliminate the extra commas for you, old browsers (e.g. IE) will choke. Not only that, when it chokes, the error message will neither be helpful nor friendly. Most likely, you won’t see an error about an extra comma. Instead some piece of your code in a completely different file will throw an error because it depended on another file that depended on this file which could not be processed correctly. The error may be “undefined function in randomfile.html”

Etiquette 2: Use more semi-colons
Just like you end a sentence with a punctuation, you should end a line of code with a semi-colon;

While javascript does not require you to end all commands with a semi-colon, this is a very good practice. Most modern browsers will fill it in for you, assuming you write clean code. However, if there is a syntax error in the code, the missing semi-colon can make that syntactic error very hard to find. It may point you to a line that is a hundred lines away from the target problem.

Etiquette 3: one command per line
When you speak, you should often space your sentences to let the listener catch up and process what you have to say. You shouldn’t ramble on without pause.

Code should be the same way.

Give each coding command a line of its own.

Something like this will just not do:
var foo = this.foo(...); var bar = this.bar(...); document.write(bar+foo); ...
If something goes wrong, you will not know which of those functions blew up on that line.

These are some lessons I’ve had to learn the hard way over the course of my life. Make good coding decisions now so you spare yourself (and others) the hair-pulling later.
Advertisements
Tagged

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: