Regarding Block Style
I went to a great talk by Douglas Crockford today. If you’re a JavaScript programmer and haven’t read any of his articles, head over to his site and get started. It’s more important than reading this blog. Seriously.
Alright. I want to show an example he used that doesn’t seem to be included in any of his articles online. This may not be exactly the same, but is close to how I remember it.
Everyone argues about where to put the starting curly-brace of a block. Usually they don’t have any substantial cause to pick one over the other, but everyone agrees one technique should be used consistently in a given program. There is a reason to choose one style over the other in JavaScript. Check out this example:
function test1() {
return {
foo: "bar"
};
}
function test2()
{
return
{
foo: "bar"
};
}
alert(test1() === undefined); // false
alert(test2() === undefined); // true
These two functions appear to only differ in their formatting. Surprised by these results?
The first function does exactly what it looks like it should. In the second, 4 different language design problems cause the program to do something unexpected while providing no errors.
- Semi-colon insertion causes the return to be a return;
- A line that starts with { starts a block. There is no block-level scope, so in this case the block does nothing. This “feature” is only there because C has it.
- The foo: looks like part of an object literal, but we’re in a block, not an object literal. This should be an error, right? No, it’s a label. Even though we’re not in code where a label could do anything, such as a for loop.
- The rest of the line after the label is the value “bar”. A value by itself counts as a statement, even though it doesn’t do anything.
Wow. That function does something wildly different than what it appears to do. The point Crockford was making here was that in JavaScript, unlike in most languages, preferring the first type of curly-brace placement helps you avoid mistakes like this one.
He also mentioned that JSLint, his free JavaScript code quality tool, is able to pick up on this kind of mistake. Try running my example through it!
No Comments »
No comments yet.
RSS feed for comments on this post. TrackBack URI

Tweet This