Unfortunate Syntax Rules
There are two things with the JavaScript syntax that really bothers me. What they have in common is that they force you to remember to add superfluous characters to your code. This makes it really easy to forget to add them, and this may cause syntax errors or bugs.
Sound familiar? Probably. First of all I’m thinking of the fact that
array and object literal values need to be comma separated. It makes
sense, [1, 2, 3] looks good when you write it on one
line. But take a look at the multi-line version:
var a = [ 1, 2, 3 ];
There’s obviously no comma after the last element, and while it still
makes sense, my opinion is that it doesn’t look good. But what’s worse
is that if we were to, say, swap row 3 and 2 we would have to remember
to move the comma to the 3 as well. I forget this all the
time. Same for object literals, and even though firefox lets you keep
the comma after the last element (IE doesn’t so I’d prefer FF to break
as well, so errors would be thrown before I got to testing for IE.) it
doesn’t allow you to forget to add the comma on the 2nd line. So time
after time I have to find out that my tests are breaking because of
this trivial matter.
So perhaps the commas could be removed, or if that would be confusing (might be hard to tell where an element ends and the next starts) put a character such as the semi-colon at the end of each element.
Even worse are switch statements. JavaScript uses C-style switches, in case you’re not familiar with the language. Whoever came up with the idea to “execute the next case after the current one unless an explicit break statement is found”? Twice in the last couple of months I’ve spent a big chunk of time looking for obscure bugs because I forgot a break statement. A clear majority of the times I write a switch, I always want to break after each case. I expect that is true for most other programmers as well. So the mistake made for the syntax was to force programmers to add extra code when they wanted the general case functionality. I hear the makers of C# saw this problem, but instead of removing the break you are forced to put it in there. Every time. So in C# you can’t have two cases share code, but I think it’s better than the original behavior anyway. So I say, remove break and make it the default behavior and add a continue statement that signals that the next case should be executed as well. Or perhaps it would be even better to remove the break, prevent cases from sharing code in this way and extracting shared code into functions instead. That’s what we normally do, and it’s fine, right?
I find the switch syntax inconsistent with the rest of the language. Switch is pretty much syntactic sugar for a group of if statements, and we don’t have this “go to the next clause” behavior there. I also have a hard time seeing anyone daring enough to use gotos for this, even if they only allow gotos to the next clause.
Post new comment