In JavaScript, curly brace placement matters: An example
JavaScript By Dave Ward. Posted March 21, 2011Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.
Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.
If you’ve been working with JavaScript very long, you probably know that you should format curly braces in JavaScript code a certain way. In fact, if you’ve watched my TekPub series, Mastering jQuery, you’ve heard me stop James and remind him that at the beginning of nearly every episode.
However, you’re less likely to have seen a clear example of why this matters or why you should care. Even when you hear advice from a trusted source, it can be difficult to heed that advice if it seems like hearsay or convention for the sake of convention.
While I was working on my recent post about extracting data objects from HTML structures, it occurred to me that some of its example code presented a great learning opportunity regarding this topic. So, I want to take advantage of that opportunity to show you a concrete example of how placing your braces on the wrong line can break your JavaScript code.
Allman, K&R, and you
The specific part of the previous post that I want to talk about is this:
return { id: $item.data('id'), text: $item.text() };
Notice how the opening brace in the object literal is on the same line as the return statement.
Placing opening braces on the same line as their corresponding control statements like that is called K&R style. Unlike most differences in coding style – most amounting to personal preference – using K&R style braces in JavaScript is important for an objective reason.
That reason is well-illustrated by looking at the alternative style in this case. That alternative, Allman style, is a style that’s more common in languages like C#. Allman style braces are placed alone, at the beginning of the line immediately after a control statement.
Modifying the previous code to use Allman style braces would look like this:
return { id: $item.data('id'), text: $item.text() };
That code is now broken. Though you can usually get away with using Allman style braces in JavaScript, returning object literals is an example of when you cannot.
JavaScript semicolon insertion can ruin your day
The culprit here is JavaScript’s infamous semicolon insertion feature. A JavaScript interpreter will parse return\n as a complete statement, assume that you forgot a semicolon at the end, and then treat it as return;\n instead.
In other words, when you write this:
return { id: $item.data('id'), text: $item.text() };
It’s actually interpreted as if you had written this:
return; // Waiter, I didn't order this semicolon! { id: $item.data('id'), text: $item.text() };
The insidious result is that almost all browsers will allow the code to execute, but the prematurely terminated return statement will return undefined instead of the object you’d expect. No syntax error, no warning; just a chunk of “working” code that behaves inexplicably.
Conclusion
Since this problem manifests itself as an undefined return value, you can imagine how painful it can be to trace that back to an artifact of where the curly brace is located. Unless you’re already aware of the semicolon insertion trap, brace placement is usually the last thing that you’d suspect to be the culprit in these situations.
The problem would have been even worse in the larger example that this code excerpt was extracted from. The object literal’s location within the .map() call would have obfuscated the root issue even farther since “mapping” a series of undefined return values would simply result in an empty array.
Key takeaway? Always use K&R style braces in JavaScript, even if it’s not the style you prefer in other languages.
Allman braces bring zero objective value to the table. Using them out of personal preference isn’t worth the mental overhead of consistently remembering that they break when returning object literals, nor the debugging morass that will inevitably crop up when you aren’t paying close attention and muscle memory takes over.
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
11 Mentions Elsewhere
- The Morning Brew - Chris Alcock » The Morning Brew #817
- PAYcast 15 » PAYcast
- Links for 2011-03-24 — Business Developer Talk
- Weekly Links– 2010_13 (50 for Web Devs & Other Geeks) :MS-Joe (Joe Stagner)
- PAYcast 16 » PAYcast
- Links for 2011-08-13 | Business Developer Talk
- Weekly Links– 2010_30 (50 for Web Devs & Other Geeks) :MisfitGeek (Joe Stagner)
- Knowledge Exchanger » Java Script Curly Braces place
- Principles of Writing Consistent, Idiomatic JavaScript | phato.blog`
- Bug of the day: JavaScript | Meg's Blog
- Minfied respond.js does not work in unpatched IE7 | Selfelected



It’s funny when I started out coding JavaScript I used the C# convention for ages. Now looking at some older code though it just looks WRONG to me and the K&R style coding in JavaScript just feels perfectly natural. It also has the benefit of saving a few bytes for the C/Rs not typed. Incidentally it’s even corrupted my C# code typing – if it weren’t for CodeRush which automatically formats my brackets (Allman style) my C# code likely would be a mixed bracket mess :-)
I was the exact same way for the longest time. My older posts all have JavaScript examples with Allman style braces. Embarrassing!
I split between them for a year or two, but finally gave up and switched to K&R in C# too. The straw that broke Allman’s back for me is how much better K&R formats for inline code in Razor views, coupled with the fact that VS won’t auto-format different C# brace styles in markup vs. code.
I’ve always done K&R. The big reason I’ve never been comfortable learning Python is the utter lack of braces. It just feels so wrong, especially since there isn’t a symbol terminating a block of code.
i started using Allman style in JS when i started using jQuery,
makes it easier to follow the trail of nested anonymous functions..
but you do make a point here, maybe the problem lies with nesting anonymous functions ;-)
Depending on where your nesting trouble lies, the new $.Deferred feature in jQuery 1.5 is a handy way to combat the deep nesting that comes with AJAX work (which seems to be one of the top two culprits for deeply nested callbacks).
yeah, can’t wait to switch to 1.5
whois Allman and why hasnt he been deprecated yet? :)
Because when you’re skimming code, you’re going to run into this:
if (x) {
y=z;
if((z == x) && isValueValid(z) && usingBadFormat(x,y,z) != Constants.BAD_FORMAT_USED)
m=n;
}
and you’re going to conclude that someone forgot a closing brace. And you’ll run into this over and over and over while skimming code 10x slower as you look to make sure that every closing brace actually has an opening brace at the end of some variable-length line. Eventually you’ll get sick of it.
I can honestly say that I’ve never encountered that problem in the roughly fifteen years I’ve been using JavaScript. If you format your code poorly, no amount of punctuation in any location will make it readable (yet, almost any editor will handle brace matching for you anyway). Just getting the indenting right makes that understandable:
Better yet, avoid the nesting-related issue altogether:
Ultimately, it’s not your job to skim code for missing braces anyway. A mismatched brace will throw a syntax error immediately (or when you JSLint your code). There’s no sense wasting human eyeball time on that unless there’s actually a brace-related syntax error, which is pretty rare if you’re using a modern editor.
On the other hand, I have helped more than a few C# developers with problems arising from trying to use Allman as they learn JavaScript. Returning an object literal is such a common task in JavaScript that it alone will eventually impact most.
Luis had a post on the same topic with the same example and the same conclusions a while ago :)
http://msmvps.com/blogs/luisabreu/archive/2009/08/26/the-semicolon-bug.aspx
I could be wrong, but I think returning an object literal is the only common example of semicolon insertion breaking Allman braces this badly. That’s why it ends up being the canonical example. Same thing in Crockford’s book too.
Ah yes, you are right, I had forgotten it was in Crockford.
The funny/weird thing is, in some browsers, you can comment out the invisible semicolon. That is, this WORKS:
This works in Chrome and IE but fails in Opera and Firefox.
Thanks for posting that; very interesting. It worked for me in Chrome, but not in IE9 or FF4.
If anyone wants to try it in their own browser, here’s a fiddle that displays
objectif it works andundefinedif it doesn’t: http://jsfiddle.net/Encosia/tXHd7/This is just a failure on JS interpreters and in general, browsers. Interpreters should stop trying to fix errors for people and tell you what’s wrong. Gee whiz wouldn’t it be a great world if GCC added a semi-colon in for me where I forgot?
I fail to see how this tolerance for errors in both JS, CSS, and HTML (and XHTML served as text/html) is a good idea.
Statements in JS end in ;, NOT \n. There should not be any exceptions.
Actually it’s not a failure of the JS interpreters but part of the ECMAScript specification. Well it may have initially been from that but ECMA 262 version 3 (what all browsers use) and ECMA 262 version 5 (what modern browsers are implementing) both define how automatic semicolon insertion should work.
Refer to section 7.9 of either documents for how automatic semicolon insertion works :).
Ok, point taken. Slight correction to OP: this is a failure of the ECMAScript specification :)
I could not agree more with the OP. When anything starts monkeying with my code, it always seem to result in way more headache than its worth. I am not talking formatting, that is gold. I am talking about changing my code: inserting statements, operators, etc. Whoever thought this was a good idea was, IMOHO, completely nuts. When you have to say, “Ok…is it my error…or was the error introduced by the interpreter/compiler/renderer…” that is just nuts.
Keep in mind that JavaScript wasn’t originally envisioned to look so similar to C/Java. To a certain extent, JavaScript started out as a Scheme dialect with Java-friendly syntax added as a concessionary afterthought. Had Java not been so popular at the time, we probably wouldn’t have semicolons in JavaScript at all.
You shouldn’t be so down on semi-colon insertion, I love it. No semi-colons for me, ever.
Doesn’t omitting semicolons make aggressive minification difficult/impossible (excluding something like CoffeeScript that compiles to semicolon’d JS, of course).
This issue is also covered in book – JavaScript: The Good Parts by Douglas Crockford. I suggest everyone who works with JavaScript to read this book as it is great.
Ok, one edge case and everyone must change their coding habits and sacrifice readability? No thanks, I think I know what I prefer.
This does raise one point, however, which is that if you do return an object literal in this way, don’t put it into Minify, as for some reason it results in a carriage return being added automatically, hence ALWAYS returning Undefined – no matter *which* way you code. Bit of a major flaw there…!
Edit: that might have just been the website: http://jscompress.com/
Edit2: Just tried that again and can’t reproduce :-/
We run jslint against our javascript as a part of our build and this is one of the default rules it enforces. It’s definitely a great tool to catch more advanced javascript gotcha’s for a young team.
No. The key takeaway should be understand the rules of javascript, specifically ASI.
To anyone curious, inimino has written a great article about the rules of automatic semi-colon insertion that clears up much of the FUD associated with it.
Pointing out a specific example of the edge case where ASI and Allman conflict and then illustrating why that case fails seems to be the exact opposite of FUD.
Anyone who wants to learn the nuance can do that and avoid the problem in the future. If not, now they have a clearer understanding of why K&R is a rule of thumb in most JS development.
I didn’t mean to infer that your article was promoting FUD, just that inimino’s article tackles much of the FUD associated with ASI. However, I still disagree with your key point that only a certain coding style should be used (to avoid unexpected ASI errors).
Hm… didn’t know about that little ASI bit. Can’t imagine why that would ever be in the spec as it’s just lazy coding IMO. I’m not fond of anonymous functions either, and that seems to be the mainstay of jQuery and other frameworks. Probably why I don’t use jQuery much, if at all.
However, the example you make is the only case that I can think of where I am forced to use the K&R placement style. In general I find K&R harder to read and avoid it like the plague. I feel that, for me, Allman is cleaner in appearance and is what I use in both C# and JavaScript.
Thanks brah, I’m just getting started with JavaScript, coming from C++ where the idea of something significant depending on whitespace is inconceivable, and I have a feeling you may have just saved me a future nightmare. Thank you for the article!
Sorry, but converting to K&R style because of the one rule about semicolon insertion with return statements is unreasonable. The readability gains for using Allman style are worth the occasional placement of a curly brace right after the return statement. Also, using the curly brace in that context is for defining an object literal; K&R specifically deals with keeping braces related to flow control on the same line.
Just because JavaScript reuses curly braces to mean object literals as well as flow control doesn’t mean K&R needs to be used in both cases.
Instead of dismissing allman style in js isn’t it more correct to always assign an object to a var before returning. So you keep the readabilty of allman style and don’t mistakenly forget to move up the curly brace when you return an object?
I don’t think you’ll find very many JavaScript developers that see Allman as more readable. It’s one of those Java/C# habits that can be tough to unlearn at first (see my first comment, in reply to Rick, for example), but it’s not something you’ll miss once you’ve discarded it.
IMO, one of the most universally unreadable things about source code is vertical length. Comparing this:
To:
Choosing the latter is an easy choice for me, even though I used to use Allman for everything and did prefer it initially.
Allman’s formating does not apply to object literals.
I learned JS before I learned C#, and I used Allman way back then. Dismissing a style just because of a flaw in the language spec isn’t valid IMO. shrage is correct in the original post. It is more correct to always assign a return value, even if it is null, than to just hang a return out there with nothing on it. With that considered, this still breaks down to a developer preference: K&R or Allman.
The latter isn’t returning
null. It’s returning the object literal. An empty return statement returnsundefined(which !==null).I’m not sure I follow what you mean about null there.
Hmm…I have to disagree. Perhaps there is preference to “vertical length” but fewer statements are never more understandable than more verbose, explicit messages. There are many, many reasons to be concise, but I have never heard the argument made that fewer statements add to readability. Your example even seems to refute your contention. Do you *prefer* the latter convention? Cool, to each his own. However, which is more readable and readily understandable by any Tom, Dick or Harry coming across your code? I strongly believe it is the first because it is more explicit as to what is going on. Even if I am not familiar with JS, I can get the idea from the first, where the second might come across as some weird language specific voodoo.
It is my very strong contention, all things equal (i.e. not considering *significant* performance improvements, etc.) more statements are ALWAYS better and thought processes of “I put all this in a single line of code!!” do not serve anyone. At all.
You got this wrong.
Curly braces are not a JavaScript language feature per se, they can be used for: blocks and object literals.
Allman’s standards does only apply to blocks, not to object literals. Not even in C#, objects go in a different line ( http://newcome.wordpress.com/2010/06/11/c-object-literal-notation/ ), why? Because they’re not blocks, it’s that simple.
There is no problem with that pattern, the problem is you’re confused.
That’s not a very constructive comment. Whatever semantics you prefer to describe it, the style that looks like Allman breaks in JavaScript if you use it to return an object literal.
Also, both looks like Allman and looks like K&R work for declaring an anonymous type in C#. I.e. both of these work:
So, there does need to be some acceptable naming for the different brace styles on object literals. What would you prefer we call it?
Wouldn’t the interpreter work like:
This coding style is common in a lot of languages: Unless I tell you different, this line ends the command sequence.
C# is just the opposite: Unless I tell you different, the next line is part of the command sequence.
(I suspect C# coders rag on VB.NET because either they don’t like the style difference, or they are too lazy to add the characters to continue a line. OK, I hate that it doesn’t support XML documentation style. Wow, I’m ragging on that, on a language blog that doesn’t know what I am talking about.)
That’s the problem. In JavaScript,
returnis a valid, complete statement by itself. Coupled with JavaScript’s automatic semicolon insertion, you end up with thisundefinedreturn problem when trying to return object literals in this format.Personally, I use Allman style for everything except object literals (because conditions are blocks, but object aren’t, as has been said). I find it significantly more readable because it matches tab indentation evenly, so you can see nesting structure far more clearly.
But I don’t think it’s reasonable to dismiss an entire coding style because of one problem, that really only comes down to misunderstanding. The example you’ve given here is (afaik) the ONLY situation in which semi-colon insertion breaks the code; and as others have said, an understanding of the situation is all you need to avoid it.
Semi-colons are important, and coders should ALWAYS use them, never relying on automatic insertion (and if it was up to me, the language woudn’t do it at all). JavaScript is not Python or Ruby — whitespace is unimportant, which is precisely why semi-colon terminators ARE important.
It’s a shame that even strict mode in ECMA5 doesn’t fix this problem. Worst language feature ever.
This applies to
throwas well since it is also a restricted production.E.g.
throw { message: 'my code has bugs!' }vs
throw { message: 'my code has bugs!' }I’d write it as {the braces should line up vertically if I did this right):
return { id: $item.data('id'), text: $item.text() };Which keeps the indent-alignment of Allman but preserves the parameter placement after the keyword “return” .
I have to. K&R bugs me. The closest thing I have to an OCD symptom. Aligned braces keep me sane.
Also
var foo = new { bar = "foo" };That’d result in some massive indenting if you used it across the board (for example, the entire body of a function would be indented past the column of the braces. That means you’d probably have an inconsistent usage where functions put the opening brace on the new line still. Yuck, IMO.
Aligned braces are overrated.. I absolutely hated K&R braces when I first started at MS, now I could never go back. The code takes up so much less vertical space, and there’s never ever been a problem with readability or easily seeing what lines up with what. It’s easy — you see a construct like a method or an if, the code inside it is indented, and theres the closing brace, right down there. How nice :) No problem.
(See above)
Am I crazy? Am I the only one who does this? Tell me why you wouldn’t do it the way I illustrated if you’re an Allman fan.
Just curious–convince me. :)
Any language or development package that “inserts” stuff for you is a timebomb, and is the primary problem here, not the brace style or usage. I
That was my comment. Apparently no one wants to listen to how this is a failure on the language specification, browsers, and the list goes on.
I don’t think it’s that anyone doesn’t want to listen, but that we’re being pragmatists. Whether ASI is a “bad part” (which I tend to think) or a “good part”, it’s not changing any time soon at this point. So, we can either complain about it, without any effect, or understand and work around it.
I think my solution shall be remembering to use them where necessary and JSLint. This is an example I sometimes forget (thank PHP for this).
var foo = {
bar: function() { alert(‘hello there’); }
}; // <– easily forgettable because other languages often do not require it or this is invalid except C++ when defining classes
PHP: class foo {} // ; optional
C++: class foo{}; // requires ;
Objective-C: class foo{}; // requires ;
Python: class foo: // very different, but in Python in general ; are always optional but the automatic placement seems a little bit more refined than JS, especially with required indentation
All these inconsistencies can get a little confusing sometimes.
The other thing I would like to see in the specification is ignoring the last comma in an object making the following possible:
var foo = {
Bob: 1,
Alice: 2,
};
Currently that is invalid and good debuggers will stop at the 3rd line. JSLint will give an error. But C and PHP both allow ending commas that get ignored and not warned about.
I used to use the K&R braces until I discovered the Smythe sequencer. This allows me to write JS code whichever way I like, and the Smythe sequencer adjusts it for proper JS execution.
I am very happy to learn that other people are consider to use the Allman method, but want the luxury of the K%R prestige braces. With a good syntax highlylight editor you can make the very attractive Allman looking but K%R working expression.
The pros for Allman outweigh the cons:
====================================
1 – Because it is the standard in C# making functions easily portable
2 – Code readability – insets are clear (what follows should have increasing insets
function f()
{
try
{
if()
{
}
else
{
}
}
catch(e)
{
}
2 – Objects are preferable to object literals for inheritance, prototyping, crossmethods, so object literals are not a sufficient reason for making changes to the rest of the code.
function obj1(a,b)
{
this.a=a;
this.b=b;
this.action = “eats”;
// Method
this.m_do = f_do;
}
function obj2(a,b)
{
this.a=a;
this.b=b;
this.action=”catches”;
// Method
this.m_do = f_do;
}
function f_do()
{
alert(this.a + ” ” + this.action + ” ” + this.b);
}
me = new obj1(“lion”, “giraff”);
you = new obj2(“cat”,”mouse”);
me.f_do();
you.f_do();
3 – When using SQL as the browser language (see: http://www.avronp.com in javascript section) it is essential to represent table as class definitions in Allman tabular form.
Vertical alignment is under rated in general, and tools like VisStudio (when the option hasn’t been turned off) that automatically remove white space and break alignment are a pain. Many is the time I’ve taken someone’s code, vertically aligned related things – not just braces, and said “Which of these is more readable?”. They say something like “Wow!”.
There is no indenting in your code example. Was that an editor formatting issue? If so, that’s another reason not to do Python, which would break.
Also, I have usually preferred K&R style, because I like to see a code block as something more closely associated with the name that starts them, and I like to see as much code as possible on the screen without excessive scrolling, so I don’t have to keep pages of code in my biological memory in order to understand it.
I do see the advantage of being able to line up braces in Allman style, and most editors seem to format it that way automatically. Because of that, I am on the fence, and don’t have any trouble following whatever is the standard of the code that I am working on.
Sorry, You have not convinced my to stop using Allman at all. You have just made a point of not returning a value like that though, or if I must, I will break from the standard Allman and using a modified version as others have posted.
To me code readability is king and Allman is hands down more readable than K&R.
I’m pretty sure the K&R style is the only way to go in JavaScript and everyone should just shut their faces and do what I say. <– Stoking the NERD RAGE! (You're welcome Dave)
I really don’t get all those people defending their choice of Allman because of its readability. To me, it never was more readable than K&R — on the contrary. When done properly, indentation is as clear as can be, without the vertical space loss.
Also, I’ve never seen a shred of evidence that either is more readable than the other. I’ve always assumed coding style to be a matter of what you’re used to, and the number of proponents on both sides tends to confirm this.
In the case of Javascript, consequently using Allman will lead to errors; not so for K&R. That makes the choice easy. And since I prefer K&R anyway – w00t!
@Avron said: “Objects are preferable to object literals”
Aaaaaah! Run for the hills!
@Martijn: agreed, when such claims are made, they should be followed by evidence.
My reasons were given above. I don’t see that you have refuted them.
Here are some more details on the last reason, which just CANNOT be done with object literals i.e. using SQL as the browser language:
// You can my site on how to define the SQLExecute function
It’s all about making complete statements. Semi-colon insertion wont happen when it will cause syntax errors, so as long as you make your line endings incomplete statements, it’s all good. For example, I had a similar issue with `return` but I was wrapping my response in `( )` rather than `{ }` http://blog.booleangate.com/development/javascript/semicolon-insertion-finally-caught-me/
I dont know if people are going to rage at Visual Studio here, but that’s what I use. Automatic K&R for javascript, automatic Allman for C#, both are good and make the code easier to read. It doesn’t get much easier than that.
The other good thing I find is that I always type in Allman, so when I try to auto-format my js and it leaves it as Allman, I know theres something wrong!
Should work identically to your code. Erm, what was your point again?
Hm. This was in reply to Avron Polakow’s post.
I concede that I would never have worked out your solution.
To tell you the honest truth, I don’t even understand your solution.
I have never come across: args.unshift(this.length)
which seems to me obtuse compared to: new SQLrow(SQLtable.length,
It would be interesting to benchmark both solutions under stress testing on all browsers to see if there are any performance advantages to either. I have always used arrays and joining instead of concatenations (for long concatenatons). I suppose the script parsers are using index registers in mode 3 to achieve such lightening speed
How would you handle the following:
- prototyping so that SQLrow became the base inheritance class for say a derived class “employee”?
- Dynamic SQL DDL commands like Create table or Drop table?
I aim for perspicacity and parsimony in code over visual appearance. I cannot see why a syntactical convention should make solutions become so complex.
You know why it’s called Crockford?
No…
Crock full of re-design
:)
Wow javascript is very powerful
Crockford has a program he confusingly calls ‘jslint’ which checks that semicolons are always used among other things. It is basically a Crockford-style checker. Or something. That said the team I was on chose to standardize on using it as part of the build process.
It checks several things. I can’t say it would have caught this, but it is one of the few things available to help in the war on semicolon insertion:
http://www.jslint.com/
KnR braces-formatting alone will not solve this – and as mentioned some teams don’t like KnR – and there is no reason they should be forced to use it. Tooling should be mature enough to allow choices.
jslint is generally worthwhile, but its semicolon suggestions still won’t help you here if you try use Allman braces.
I see your point but I would prefer not to see a return statement like that. At the very least it should be:
return getItem();
or better yet:
var item = getItem();
return item;
Seems more readable.
No one has mentioned the possibility of adding a backslash after the return statement to fix the problem and still keep Allman style:
return \
{
id: $item.data(‘id’),
text: $item.text()
};
I find the resulting dense code of K&R style unreadable. Vertical space? Put your code on the left widescreen monitor and rotate it. We’re not using 13-inch monitors and ED anymore.
So to comply with JSLint I find myself doing
if (expression) {
//code
} else {
// code
}
JSLint really has helped me and my team with Javascript a lot. It’s just this one thing that annoys me.
I’d agree that for uncommented code K&R style looks better.
But adding extensive comments to that K&R formatted code makes that code become unreadable and look dreadful.
The more comments you write in your code (line-by-line) the more reliable your code will be (at least up to a ratio of 1 line of comment per 1 line of code).
The cleverest programmers, i.e. those producing the most reliable code, are those who know not to be clever. When you see their code, your first impression is to dismiss them as simple and unsophisticated, possibly even pre-judging them as being of low intelligence.
But the results – the reliability and performance of what is produced – speak for themselves.
Any extra time they spend thinking through and typing the comments is vastly outweighed by the enormously reduced debugging time that follows (often zero).
Unfortunately the K&R style discourages such extensive in-code commenting due to the mess it makes of code with such comments.
I’ve found lots of errors (both small and large) upfront before even firing up a compiler, or running a line of code, purely from the strategy of extensive commenting.
Having never encountered the situation you present, it would take far more than such an uncommon situation to convince me to give up extensive commenting …. which would surely be the result if I were forced to adopt K&R style.
And moreover, it doesn’t say much for the credibility of a programming language if you’re forced to adopt a sub-optimal coding style, simply because the compiler is trying to accommodate people who can’t even get the basics of adding a ‘;’ correct.
@Fred Jones… I agree on all points. This article is interesting in the sense that I am now warned about (what I consider to be) a faulty javascript interpreting scheme… but it’s not enough to sway me from Allman.
Simple, clean and clear is my motto – and I think Allman helps.
sorry, “correct” or not, K&R style is just excruciatingly hard for me to read when there are lots of nested blocks. It’s ALOT easier to read when you can line up the opening and closing braces of a block to tell where it begins and ends. Whoever designed JS to work with this semicolon insertion crap is an idiot…
You may not agree with ASI (I don’t care for it either), but I’m pretty sure Brendan Eich is not an “idiot”.
Agreed… Brendan Eich is not an idiot. In the words of Douglas Crockford “I challenge you to design and implement a language in 2 weeks and have it come out half as good as Javascript”.