As I understand it, the main point of that section is what to do with the onclick handler vs. what to do with the href attribute. You can follow the suggested practices regardless of whether you put your onclick code inside the element (as in the simple example) or in the script tag (as you rightly recommend).
Yeah, the author is basically telling you to use what is now considered a bad practice (onclick) instead of a worse practice such as... href="javascript: dostuff()"
Ever since the term "unobtrusive javascript" came into play, it's been considered best practice to have all scripts loaded externally, then select the element and attach a listener to it.
If nothing else, it goes against the author's own rule of never using eval, albeit in this case it's an implied eval rather than explicit call to the eval() function.
Yeah, I didn't see a date anywhere, but parts of this advice seem old. That doesn't matter for some things that will never change, but nobody should be writing onclick attributes in 2012.
I have found that when you're looking for JS help or references, you should use the most recent available.
Crockford's "JavaScript: The Good Parts" is the gold standard for best practices. Pretty much anyone who works in JS will recommend it. Here's a video which is a condensed version of what's in the book: http://www.youtube.com/watch?v=hQVTIJBZook
I used to write (and probably still do, but to lesser extent) horrible Javascript. Nearly all older guides (anything older than a year) never focused on Javascript guidelines - and then I ended up watching Crockford videos.
My understanding of Javascript has increased; I now think of Javascript as a proper language to code in and not just a collection of statements to make HTML elements move/change-color. Crockford videos are a must see!
The only issue might be that there is a lot of repetition of concepts between videos and sometimes it gets boring, but it is always worth it.
Do people actually use the object-as-an-associative-array property access as a general practice?
I use it when it's useful, but if the name of the property should not be determined at run-time, I always do the dot notation. I've never heard of anyone taking issue with it, either.
The original quote is "When accessing object properties that are determined at run-time or which contain characters not compatible with dot notation, use square bracket notation." To which should be added: object properties that are reserved words in the language.
The most common problem here is people using the dot notation for properties like "object.default" or "object.class" that are syntactically invalid.
The rest of the article is a strange mix of good advice and some cases of pretty-bad code being presented as better than very-bad code.
I agree completely. This article mixes obvious no-no's like using var and avoiding cluttering the global namespace with headscratchers like the one you mention.
This article would more accurately be titled best practices for DOM interactions since most of the suggestions deal with DOM issues rather than pure language issues (and most of these are easily dealt with through the use of a good library like jquery).
The Google Javascript style guide someone mentioned above is much more relevant to pure language issues, and is the one style guide I reference frequently (or should reference frequently).
I think JSLint should probably get a mention when discussing best practices. It can be rather picky but most options have toggles. (I'm particularly not fond of having to put extra spaces around operators. var j=2 looks better to me than var j = 2)
It's well worth the effort writing code that conforms to JSLint or JSHint. There are a few rules which seem excessive but if you code in a team then it's so much easier knowing that all code follows a standard.
When another programmer asks me to fix bugs in some code, I get them to make it parse JSHint first. Most of the time, fixing errors to make it conform either fixes the bug or helps them understand the code enough to fix it themselves.
There's some good stuff here, including stuff that I've learned over the years and some stuff I didn't yet know. But I don't quite understand this one:
Square bracket notation is awesome for mixing in variables - it saves you from using the evil eval() - and obviously BAD is worse than GOOD, but if you have no variables what about this:
> ?: document.forms.formname.inputname
If there's no functional difference it's shorter and simpler than GOOD
Neither is great practice, in my opinion. This page looks dated in its recommendations. Any sane JavaScript that works with DOM elements should use a DOM abstraction like jQuery. Leave document.forms.fooinput.parentNode.firstChild.nextSibling.godhelpme to die in the grave of DHTML and incompatible DOMs from the IE6 era.
I tend to use document.forms['foo'].elements['bar'], here's why:
I use the elements collection because the behaviour of adding each input as a property to the parent form element is a mistake.
I use the bracket notation because it highlights the difference between the implementation symbols and the actual data which is being manipulated. What I mean is that I see a property specified with the dot notation on the same level as an identifier and as such its name is just to remind us humans of its purpose, whereas a property accessed using bracket notation is important both to us and to the program since it specifies a data point.
Perhaps it implies that you've extracted those names into some kind of constant or configuration object or view model that you're using throughout the system; if they change, you change them in one place and the square bracket version keeps working.
I personally find it more useful to deal with forms using some kind of abstraction on top so I doubt I'd use either variations in anything other than a very simple page.
IIRC it has to do with backwards compatibility, but I believe that the property accessors have been there for quite a while so I don't know if it is even valid for most of the browser targeted today. It may be one of those old best practices that is no longer relevant with the exception of people targeting older browsers.
I don't agree that using the unary plus operator is a best practice for string->number conversions. Best practices should advocate maintainability and clarity - in this case parseFloat is the better choice for obvious reasons. Just be aware that parseFloat and unary + aren't exactly equivalent: parseFloat("10x") === 10, +"10x" === NaN.
And no, JavaScript is not a "non-typed language." AFAIK JavaScript is both dynamically and weakly typed. Being in the latter category does mean that it will implicitly convert values to other types in certain scenarios.
I don't understand why he would recommend unary as a replacement for casting. It obfuscates the intent of your code, which is especially concerning since this reads like a guide for beginners.
That only applies to parseInt because it tries to guess the radix if one isn't supplied. parseFloat assumes base 10 and doesn't accept a radix argument.
I use Komodo IDE. Both their IDE version and the free Komodo Edit have near-realtime syntax checking for JavaScript, Python, Ruby, Perl, PHP, and one or two other languages. You get red squiggly underlines for syntax errors, green squigglies for warnings. It's quite nice to know that my code is at least free of syntax errors before I even save the file.
Additionally, you can configure JS[HL]int to use flymake[3]. The trick is to improve performance by having it talk to a running JavaScript process (e.g. a node server) instead of starting a new one each time.
I code with SublimeText 2, which validates JS files as soon as I save them using a local Node instance of jshint.com and a plugin called SublimeLint. It took a while to set up but the productivity gain is well worth it.
Nice. Quick off-topic question: assuming you have experience with TextMate, do you find SublimeText 2 to be slightly better than TextMate or significantly better?
I use SublimeText on Linux and haven't got any first-hand experience of TextMate. I have seen coworkers use it and as far as I can tell, the main difference between them is SublimeText is much faster. It loads in under 1 second on an old PC and working with files feels instantaneous. It's also available cross platform so you can get the same experience on any computer. Well worth installing the trial then shelling out for the licence IMO.
I general I have heard and seen that SublimeText is better than TextMate and look good as well. The fact that most of the plugins from TextMate work with Sublime means it is a no-brainer which to use.
javascript-tools for TextMate. Calls JSHint on every save and quickly gives you the number of errors. Also allows a full check using JSLint or Closure linter, minifying etc.
I meant something that would not be detected when compiling to JavaScript from CoffeeScript. Maybe I got it all wrong and CoffeeScript just translates without performing any checks. Also I thought maybe the subset of code you can write with CoffeeScript can't be invalid, if it were wrong it just wouldn't work.
WHAT?
No, you do NOT mix JavaScript into your HTML elements. Total disregard for separation of concerns, maintainability nightmares abound.
You put script, surprisingly, into the <script> tag.