The semicolon bug
Since I’ve started blogging about JavaScript, I thought that it would be ok to share with you one of the most embarrassing bugs I’ve introduce in a code base. Now, when I look back, I do find it funny, but I can tell you that I didn’t laugh about it at the time. The code is really simple, but I guess it shows why I started putting braces on the opening line…
function doSomething(number) {
//do some very interesting stuff here
//return object
return
{
x: number + 1
};
}
var a = doSomething(1);
alert(a);
Really innocent, right? Unfortunately, it returns undefined instead of the literal object I was trying to build. Btw, this will only happen when the returned object only has one property. If you had more than one, then you’d be getting a parsing error (in JavaScript, it’s common to use anonymous objects for passing data around and it’s not uncommon to fill only the “used” fields).
I guess that if I had read the spec I would have found that JavaScript will automatically insert the ; after certain statements. Here’s what the 1.3 spec says about this topic:
Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
I guess that the moral of the story is that in JavaScript, the C K&R style should be used always.
P.S.: a final note to say that I’ll be receiving Douglas Crockford’s book in the next couple of days. That means I’ll be learning a few more tricks to share with you :)