

Javascript Best Practices - googletron
http://www.javascripttoolbox.com/bestpractices/

======
bdg
> 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.

~~~
epochwolf
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>

~~~
bdg
1\. Pollutes the DOM

2\. Violates separation of concerns

3\. Complicates maintainability

4\. Events are bound directly to elements rather than bubbling and being
managed via delegation.

~~~
mayanksinghal
I don't use use onclicks either but from the source of this page:

    
    
      onclick="return vote(this)"

~~~
jonah
This page uses tables too.

[edit] my point was to not take this site as an example of best-practices...

------
markerdmann
This is also a great reference:

[http://google-
styleguide.googlecode.com/svn/trunk/javascript...](http://google-
styleguide.googlecode.com/svn/trunk/javascriptguide.xml)

~~~
ckhoo
Thanks for the link. Google's Javascript style guide in conjunction with this
article's best practices really helped.

~~~
funkah
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>

~~~
mayanksinghal
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.

------
nailer
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
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.

~~~
djacobs
s/ghetto/standard/

------
scarmig
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
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.

------
grannyg00se
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)

~~~
marcins
There's also JSHint (<http://www.jshint.com/>), a fork of JSLint with a bit
more configurability.

------
joshuahedlund
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
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.

------
cdsanchez
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.

~~~
VMG
careful

    
    
       parseFloat("08") === parseFloat("09") === 0
    
    

<http://stackoverflow.com/questions/850341>

~~~
cdsanchez
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.

~~~
mikemaccana
Oh that's neat. Thankyou.

------
googletron
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?

~~~
dave1010uk
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.

~~~
techiferous
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?

~~~
dave1010uk
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.

------
manojlds
This is way old. Hope someone doesn't start following this. Many of the points
aren't even valid now.

------
loftsy
I've found this to be an excellent set of guidelines though not all of this
works on all js implementations.

<https://live.gnome.org/GnomeShell/Gjs_StyleGuide>

------
southern
Also see <http://bonsaiden.github.com/JavaScript-Garden/>

------
googletron
I like alot the conventions mentioned here. It would make development a lot
more pleasurable.

