256 points · by raganwald · 14y ago · 133 comments
- "Why I use minimal semi-colons in Javascript"
- "ASI is broken but I like it"
Honestly I'm shocked at the defense of this practice (of ASI "abusage"). It speaks loudly to Jacob's (fat@githib) ranking of ego-stroking and showboating over creating readable code, particularly for a library "Designed for everyone, everywhere" [1].
I'm confounded that such an attitude can survive in a large engineering organization like Twitter. Google's style guide [2] specifically prohibits this ("Always use semicolons.") and yes, this is the same standard we use internally for writing Javascript.
Just because you can doesn't mean you should. FFS, just get over yourselves and your hipster bullshit and use semi-colons.
[1]: http://twitter.github.com/bootstrap/
[2]: http://google-styleguide.googlecode.com/svn/trunk/javascript...
If he wrote Bootstrap by himself, he's free to call every single user an idiot if he wishes, but when it's being released as a Twitter product, one would think Twitter would demand some modicum of respect to be shown. Can you imagine a Googler acting this way on the Chromium or Android projects? Yeah, there are decisions made on those where people aren't happy, but the comments aren't laden with zingers either.
If Douglas Crockford comes down and tells me I'm doing JavaScript wrong, I would hope I'd show a bit more respect to someone who's most likely my better.
My observation of open-source community dynamics tells me that being hostile is an effective way to lead a large community. I've noticed that contributors act more carefully around someone who is mean to people in general and that these people attract wide followings at conferences. (There are certainly exceptions, though, like Larry Wall.)
Can you imagine a Googler acting this way on the Chromium or Android projects?
Being nice also works, but if you compare Chrome's reach to this Javascript framework's reach and use that to scale the number of contributors, you'd expect a lot more contributions to Chrome.
I think fat is a jackass, but if he wasn't, I never would have heard about this project, which now has multiple front page articles on multiple tech sites. I imagine this is good for Twitter.
No, those are the exceptions. Being opinionated and ready to say no, however, is necessary.
I'm not surprised. A bit disappointed, but not surprised.
Have a look at the original OAuth specification sometime. Note how they misuse the word "key" to mean "identifier". I can't imagine that anyone writing a crypto specification wouldn't know that this would be confusing; I think it's more likely that the person just didn't care. Also, there's the fact that the whole thing could have been written as just a way of getting Basic authentication credentials, rather than making up a whole new authentication scheme.
And then there's the hashbang thing...
Thank you. I agree both of these show a casual disregard for "how the real world works", where not everyone is a "rock star", some are lowest common denominators using the web as best they can (and good for them for even trying!), and some just need to get things done.
Every extra exception you require in a user's mind makes your work and the web in general just that little bit less accessible.
That it is being done for "style" in an arena of notoriously unsophisticated users, really feels like a giant middle finger.
Kudos to Google for their style guide freeing up this particular "exceptions" pigeonhole from a JS programmer's mind, so she can use the synapse to get something done instead.
// Using JS in the real world since Netscape 2.0.
[1]: http://googlewebmastercentral.blogspot.com/2009/10/proposal-...
"Do your best to never use a semicolon. This means avoiding them at line breaks and avoiding multi-statement lines. For more info, read Mislav's blog post [2]."
FWIW, I agree with the Google style guide. Maybe I'm interpreting it wrong, but ASI struck me as a fail-safe to protect coders that forgot the occasional semicolon and was later mis-identified as a feature. Having Brendan Eich weigh in on this is akin to having Thomas Jefferson pop his head into the Ninth Circuit and clarify an issue over Constitutional intent. If it were me, I'd listen to Thomas Jefferson.
My advice on JSLint: don’t use it. Why would
you use it? If you believed that it helps you
have less bugs in your code, here’s a newsflash;
only people can detect and solve software bugs,
not tools. So instead of tools, get more people
to look at your code.
Unless I'm missing something, that easily qualifies as the dumbest thing I've read on the net in the last week--and I've been to /r/politics.As I noted in my blog, it's not just (, either. ( is by far the likeliest source of trouble, but / + - [ all can serve as infix operators or prefix operators or (in the case of /) lexical delimiters.
Which is easier to remember, the rules in [2] plus the full "when you must use a semicolon because it is not optional" rule? Or the rules that people who know C, C++ and Java follow?
YMMV, but it's no slam dunk, and going "light" on semi-colons risks disastrous bugs. Going heavy tires out readers a bit with chicken-scratching but carries little risk of adding bugs (the worst case is if(C);T -- oops, and empty statement linting helps).
As usual with programming, there is no substitute for thinking and practicing, learning from the bottom up, and avoiding bad religion.
Personally I don't see the point in omitting something that leads to known problems instead of including it and encountering zero problems.
Devil's advocate here: could one argue that taking advantage of ASI everywhere can make it safer, because it forces you to be fully aware of ASI?
Suppose you always put in semicolons. You can STILL get bitten by ASI. The classic example is
return
{
...stuff...
};
ASI is going to put a semicolon right after the return and break your code.Someone who strives to take advantage of ASI everywhere they can is going to remember that ASI is going to apply on that return, and they will code the above so as to take it into account.
I really don't want to deal with this kind of stuff:
https://github.com/twitter/bootstrap/issues/3057#issuecommen...
(Just like I don't want to deal with those massive ==/!= tables.)
What really surprises me is that such a large number of people are quick to attack someone for writing legal code simply because they disagree with the style used. It feels awfully close to attacking someone for using a different bracing style from your preferred bracing style.
Whenever I've been asked this, I've pointed people at the JSF-AV coding standards or MISRA.
> What really surprises me is that such a large number of people are quick to attack someone for writing legal code simply because they disagree with the style used.
The important part of the lifecycle of a piece of code isn't the writing of it. It's the maintaining and rewriting that matters. If one coding style makes it easier to introduce errors than an alternative, that's a bad thing. It's not an aesthetic concern. Semicolon-less JS is demonstrably less robust.
That might even be useful.
Reading this "debate" makes me thankful for the Python Community and their stance on "readable code" above all else.
Thus people are inferring this fat fellow is doing it only out of illogical, ego-based personal preference, because nothing else makes sense.
I’m not saying they are right — I couldn’t possibly know — but given the facts, it’s a reasonable assumption.
Our code needs to be maintainable for inexperienced developers. I don't want to make it easier for them to make mistakes and I don't want them to ponder rare (though valid) syntax. I feel this is a valid reason to maintain this rule.
// This we can all understand
clearMenus();
if(isActive) {
$parent.toggleClass('open');
}
Once a developer understands ASI and other details he is free to feel elated with his new-found knowledge, but I'd prefer if he choses to know rather than to apply these powers. "ASI [“Automatic Semicolon Insertion”] is an error correction
procedure. If you start to code as if it were a universal
significant-newline rule, you will get into trouble."—Brendan EichIf you try to take your key with you at all times, the super will save your bacon once in a blue moon when you forget your key. On the other hand, if you think of the door as only needing a key when you wish to have it opened on nights and week-ends, you are on your way to trouble.
But you don't need analogies to understand why ASI is a bad idea. ASI means that when you leave out a semi-colon you get unexpected behavior instead of a syntax error. Failure is always better than the unknown. At least then there's a chance the bug will be found and fixed.
<a onClick = "someFunc()" > ...
> Error, missing semicolon after ")" on line 1
That could get pretty annoying pretty fast, and simple little event handlers like these were probably the main use of JavaScript for the first x years. It also matched the existing philosophy of HTML which was to really go out of its way to make sense of whatever was in the file.
Now of course, the constraints are different: people want to use JavaScript for huge codebases and serious projects, so it makes sense that these decisions are no longer appropriate.
"ASI is (formally speaking) a syntactic error correction procedure."
Perhaps I've worked too much in teams, but surely "path of least resistance" has to factor some, right? I mean, if the choice is add a semi-colon to a line in a file versus asking somebody else to rewrite the compiler to be able to accept it, surely common sense would just be to add the semi-colon.
It doesn't mean that you're wrong, or that your code is broken, or that Crockford is smarter than you... but now you have code that works and compiles and that people can use.
Surely, that's gotta count for something, right?
Sure it is the easier solution right now. But in the long run that would mean the Crockford would be able to dictate the style of Javascript to whatever the hell he wants.
Given how important Javascript is now (and will be in the future) we cannot allow any one person to retard the entire future.
Anyway use Googles closure compiler -- it can actually handle Javascript.
So long as he keeps building tools and utilities that people rely on, and that people use, he is at least influencing the direction of Javascript and, knowing that, I'd think one might take heed when Crockford says "this will break in the future", as he happens to have more insight into the language than most.
I understand that he wasn't polite, and I certainly understand the desire for the 'asshole' to be proven wrong. And maybe he is. Of course, that doesn't make him wrong, and it doesn't mean that he's "retarding the future" either, necessarily.
But the fact that jsmin is perhaps the most widely deployed JS minification utility does matter, whether anyone chooses to accept it or not.
And if you really think that he is retarding the future, the correct answer probably isn't to bicker about it on the internet, but to create a better compiler (or work on getting a better compiler accepted) as de facto.
At the end of the day though, Fat is the guy who has to deal with all the tickets talking about 'This doesn't compile in jsmin', and I'd think his life would ultimately be better off if he just added a semi-colon.
Of course, that's my opinion only, so take it for what it's worth.
The fact that they return the controlling operand is quite useful. Consider a situation where you want to check the property of an object, but don't know if that object is null:
var foo = obj && obj.bar;
I find this much more readable than: var foo = null;
if (obj) {
foo = obj.bar;
}
You can accomplish the same thing with a ternary operator, but it's longer and, to my eyes, less scannable: var foo = obj ? obj.bar : null;
Also useful when setting optional parameters: function myFunc(foo, bar) {
foo = foo || {};
bar = bar || 'default_value';
}
(take care however: the empty string evaluates to false, as does [] and 0)The issue is abusing && or || as the whole of an expression statement, instead of using if.
var foo = obj && obj.bar; // great
!isActive && $parent.toggleClass('open'); // smelly
if (!isActive) $parent.toggleClass('open'); // better if (!isActive) {
$parent.toggleClass('open');
} // best
Damian Conway of Perl fame wrote an excellent style guide for C in the early/mid 90s which I'm pretty sure explained why (I can't find my copy):Programmer A:
if (!isActive) $parent.toggleClass('open');
Programmer B: if (!isActive)
$parent.toggleClass('open');
doSomethingElse();
Oh dear. // okay
if (!isActive) $parent.toggleClass('open');
// not okay
if (!isActive)
$parent.toggleClass('open');
That way you know when you change it to two lines, you have to add curlies.https://github.com/h5bp/html5-boilerplate/blob/master/index....
Your post has made me realize however that I'm not sure if the language I'm reimplementing is meant to be value preserving in the case of those operators where an explicit corrosion from the a type to Boolean has been defined. Shows how often they're used like that in production code I guess.
Be liberal in what you accept and conservative in what you send (i.e. just use semi-colons) and your systems will work and play well with others being interoperable.
While I use semicolons myself, it seems like jsmin should conform to the js spec as long as the spec allows the behavior.
Shipped software should try to work or be usable in the shipped format, get funky behind the product layer if you want.
Here the minified javascript that everyone uses, should just work with the current infrastructure. If it doesn't, provide the tool that fixes the problems for people to ship with.
Googles closure tools actually do parse the Javascript and can properly minify them better.
1. "X is stupid" post
2. "But I like X" posts 3. "X is stupid, but I like it anyway!"https://github.com/twitter/bootstrap/commit/575f18aaf49abb02...
https://github.com/douglascrockford/JSMin/commit/5ca277ea452...
At least some good has come of this, even if it did come with the baggage of a massive Internet Argument.
Quotes: On the use of '&&' instead of an 'if' statement: "If you were really having fun with it you could lose the if all together... Each is perfectly valid. Each behaves the same. It’s just a matter of preference and finding the style that makes most sense to you." JSLint is described as a "unnecessarily strict linter". "The majority of lines however don’t end with semicolons because they simply aren’t necessary and I prefer the minimalist aesthetic. For me, \n character is enough and the semicolon character is redundant."
... IMHO: Don't be a JavaScript hipster. Add semi-colons.
You're not the only person reading your code. Your code isn't just being parsed by five wholly different javascript engines, it's also being parsed by the brains of every programmer who chooses to read your code.
Expecting others to learn a few stupid rules and lame syntax hacks in order to understand and match your style seems moronic. And defending the decision by noting that "the spec permits it" is doubly so.
I think the same should apply here, the minifier should handle the language as specified, if it can't then it is has a bug.
I wish Brendan was not as skilled a hacker as he was. It's an amazing achievement that he produced Javascript in such a short time. Unfortunately it ended up having the sorts of flaws that are inevitable with such a timeframe, yet it was "good enough" so that everyone decided it was easier to live with the flaws than break compatibility and fix them. If the initial version of Javscript had been worse, we might be using a much better version today.
And we should keep using it in 2012, 17 years later?
Good luck displacing JS. I mean that sincerely, especially if you work in the open. Dart had a rough start but even ignoring that, I don't think it will succeed. We'll see.
Can we reconsider using this thing as the assembler for the web? Can we come up with a sane, cross-platform bytecode standard?
[1] about 3/4 into this interview: http://channel9.msdn.com/Shows/Going+Deep/Expert-to-Expert-Erik-Meijer-and-Lars-Bak-Inside-V8-A-Javascript-Virtual-MachineCoffeeScript is far from perfect--it has syntax quirks of its own--but it's more pleasant for me to write in, being used to Python and Ruby. (And, yes, I understand JavaScript too; I just don't like the syntax.)
Eventually transcompiler languages will evolve to take advantage of different JS engine improvements. So far, this isn't a goal of CoffeeScript, but other abstraction layers might already be doing that.
I wonder what opportunities there are here that haven't been exploited yet and that don't require replacing JS with a new language. For example, could JS implementors define a more-easily-optimizable subset of JS? Then transpilers seeking performance could target just that subset.
Mentioned in http://www.aminutewithbrendan.com/pages/20101122.
JS is becoming the compiler target "bytecode", without needing verifiers or new and complex standards to be adopted by multiple browser vendors.
JS has gaps as a target language, for sure. We are working on filling them (e.g. 64-bit and other int types).
These are easy bugs to fix compared to creating a new, portable, and future-friendly bytecode standard in addition to keeping up with a competitive JS engine. Since JS is incumbent, it's hard for any browser vendor to justify a new thing with zero users at first, and too much risk of non-standardization or JVML-like albatross status.
Crockford is making a change in JSMin: https://github.com/douglascrockford/JSMin/commit/5ca277ea452...
Jacob changed the code to be compatible with existing JSMin: https://github.com/twitter/bootstrap/issues/3057#issuecommen...
There, now don't we all feel better?
http://news.ycombinator.com/item?id=3584635
https://github.com/twitter/bootstrap/issues/search?utf8=✓...
They worked around the bug some time before Crockford refused to fix it.
JavaScript falls between two stools and that's bound to cause problems.
I don't have enough fingers to count names called in both threads. Why is this subject harboring so much emotion?
clearMenus()
!isActive && $parent.toggleClass('open')
and parses it the same way it would have done clearMenus() !isActive && $parent.toggleClass('open')
On the output side, using ; is simpler to program (A\nB only means A;B in some cases, depending on B). And you'll receive fewer flames for it. \n can easily get turned into \r\n
Whitespace is harder to see when debugging (especially with word wrap)
Convention