top | item 3502003

Javascript Best Practices

92 points| googletron | 14 years ago |javascripttoolbox.com | reply

58 comments

order
[+] bdg|14 years ago|reply
> Use onclick In Anchors Instead Of javascript: Pseudo-Protocol

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.

[+] joshuahedlund|14 years ago|reply
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).
[+] Hexx|14 years ago|reply
I think this just may be an old page.
[+] epochwolf|14 years ago|reply
What's wrong with putting a single, reusable function call in onclick?

    <a href="/posts/1244/comments/new" onclick="Comment.new(this); return false;">New Comment</a>
[+] funkah|14 years ago|reply
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.

[+] nailer|14 years ago|reply
For HTML 5 All you need is:

    <script>
The type isn't necessary anymore. We know it's JS.

See http://www.w3.org/TR/html5/scripting-1.html

[+] bsimpson|14 years ago|reply
Unless you're using <script> as a ghetto <template> node (e.g. handlebars) or for WebGL. But yeah, nobody cares if you write JS without @type.
[+] scarmig|14 years ago|reply
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.

[+] asolove|14 years ago|reply
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.

[+] jnbiche|14 years ago|reply
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).

[+] grannyg00se|14 years ago|reply
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)
[+] dave1010uk|14 years ago|reply
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.

[+] googletron|14 years ago|reply
yeah thats more syntax issue. alot of the time when I hate reading javascript, when it has no structure to it.
[+] joshuahedlund|14 years ago|reply
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:

> GOOD: document.forms["formname"].elements["inputname"]

> BAD: document.formname.inputname

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

[+] pak|14 years ago|reply
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.
[+] locci|14 years ago|reply
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.

[+] brunoc|14 years ago|reply
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.

[+] kls|14 years ago|reply
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.
[+] keturn|14 years ago|reply
I had some linting tool yell at me about this recently. It said something like '''forms["formname"] better written as forms.formname'''
[+] cdsanchez|14 years ago|reply
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.

[+] bsimpson|14 years ago|reply
Casting with Number is also acceptable.

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.

[+] googletron|14 years ago|reply
what do people use to make sure the JavaScript they write is valid, as they write it. Not something I run on my code after the fact?
[+] Stratoscope|14 years ago|reply
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.

I recommend the 7.0 release candidate:

http://downloads.activestate.com/Komodo/releases/

More info:

http://www.activestate.com/komodo-ide http://www.activestate.com/komodo-edit

[+] dave1010uk|14 years ago|reply
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.
[+] plf|14 years ago|reply
I'm learning CoffeeScript right now, is what I write using it always valid JavaScript?
[+] s3b|14 years ago|reply
I use jshint as a vim plugin.
[+] manojlds|14 years ago|reply
This is way old. Hope someone doesn't start following this. Many of the points aren't even valid now.
[+] googletron|14 years ago|reply
I like alot the conventions mentioned here. It would make development a lot more pleasurable.