News for hackers. Stuff that matters.
Re:Javascript Best Practices by bdg on Monday January 23, 2012 @04:39PM (#3502251)
> 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.

Re:Javascript Best Practices by joshuahedlund on Monday January 23, 2012 @05:13PM (#3502412)
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).
Re:Javascript Best Practices by firefoxman1 on Monday January 23, 2012 @11:23PM (#3503453)
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()"
Re:Javascript Best Practices by iamds on Tuesday January 24, 2012 @08:26AM (#3504602)
what is now considered good practice?
Re:Javascript Best Practices by firefoxman1 on Tuesday January 24, 2012 @01:25PM (#3505957)
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.
Re:Javascript Best Practices by Hexx on Monday January 23, 2012 @06:08PM (#3502630)
I think this just may be an old page.
Re:Javascript Best Practices by mrpollo on Monday January 23, 2012 @07:12PM (#3502816)
Surprisingly best practices dont last much on the web
Re:Javascript Best Practices by epochwolf on Monday January 23, 2012 @06:35PM (#3502719)
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>
Re:Javascript Best Practices by bdg on Monday January 23, 2012 @11:10PM (#3503415)
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.

Re:Javascript Best Practices by mayanksinghal on Tuesday January 24, 2012 @01:24AM (#3503719)
I don't use use onclicks either but from the source of this page:

  onclick="return vote(this)"
Re:Javascript Best Practices by jonah on Tuesday January 24, 2012 @01:44AM (#3503756)
This page uses tables too.

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

Re:Javascript Best Practices by lazerwalker on Monday January 23, 2012 @06:57PM (#3502784)
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.
Re:Javascript Best Practices by funkah on Monday January 23, 2012 @11:50PM (#3503528)
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.

Re:Javascript Best Practices by markerdmann on Monday January 23, 2012 @04:08PM (#3502131)
Re:Javascript Best Practices by ckhoo on Monday January 23, 2012 @06:04PM (#3502608)
Thanks for the link. Google's Javascript style guide in conjunction with this article's best practices really helped.
Re:Javascript Best Practices by funkah on Monday January 23, 2012 @11:54PM (#3503536)
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
Re:Javascript Best Practices by mayanksinghal on Tuesday January 24, 2012 @01:29AM (#3503731)
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.

Re:Javascript Best Practices by nailer on Monday January 23, 2012 @07:05PM (#3502803)
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

Re:Javascript Best Practices by ryanac on Monday January 23, 2012 @07:25PM (#3502846)
Interesting, just checked and this is the same for the style tag (no longer requires type), never knew that they have defaults now. :)

http://www.w3.org/TR/html5/semantics.html#attr-style-type

Re:Javascript Best Practices by bsimpson on Monday January 23, 2012 @10:35PM (#3503345)
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.
Re:Javascript Best Practices by djacobs on Monday January 23, 2012 @10:59PM (#3503393)
s/ghetto/standard/
Re:Javascript Best Practices by scarmig on Monday January 23, 2012 @04:34PM (#3502230)
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.

Re:Javascript Best Practices by asolove on Monday January 23, 2012 @04:40PM (#3502254)
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.

Re:Javascript Best Practices by jnbiche on Monday January 23, 2012 @06:46PM (#3502755)
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).

Re:Javascript Best Practices by grannyg00se on Monday January 23, 2012 @04:12PM (#3502146)
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)
Re:Javascript Best Practices by marcins on Monday January 23, 2012 @04:25PM (#3502201)
There's also JSHint (http://www.jshint.com/), a fork of JSLint with a bit more configurability.
Re:Javascript Best Practices by dave1010uk on Monday January 23, 2012 @06:01PM (#3502598)
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.

Re:Javascript Best Practices by googletron on Monday January 23, 2012 @04:15PM (#3502157)
yeah thats more syntax issue. alot of the time when I hate reading javascript, when it has no structure to it.
Re:Javascript Best Practices by joshuahedlund on Monday January 23, 2012 @04:43PM (#3502272)
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

Re:Javascript Best Practices by pak on Monday January 23, 2012 @10:58PM (#3503391)
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.
Re:Javascript Best Practices by locci on Monday January 23, 2012 @07:57PM (#3502924)
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.

Re:Javascript Best Practices by brunoc on Monday January 23, 2012 @04:59PM (#3502346)
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.

Re:Javascript Best Practices by kls on Monday January 23, 2012 @05:03PM (#3502368)
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.
Re:Javascript Best Practices by keturn on Monday January 23, 2012 @05:08PM (#3502385)
I had some linting tool yell at me about this recently. It said something like '''forms["formname"] better written as forms.formname'''
Re:Javascript Best Practices by cdsanchez on Monday January 23, 2012 @10:04PM (#3503263)
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.

Re:Javascript Best Practices by bsimpson on Monday January 23, 2012 @10:38PM (#3503351)
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.

Re:Javascript Best Practices by VMG on Tuesday January 24, 2012 @12:37AM (#3503626)
careful

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

http://stackoverflow.com/questions/850341
Re:Javascript Best Practices by cdsanchez on Tuesday January 24, 2012 @12:50AM (#3503654)
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.
Re:Javascript Best Practices by mikemaccana on Tuesday January 24, 2012 @03:20AM (#3503944)
Oh that's neat. Thankyou.
Re:Javascript Best Practices by VMG on Tuesday January 24, 2012 @02:43AM (#3503874)
whoops, got out of bed too early
Re:Javascript Best Practices by googletron on Monday January 23, 2012 @05:26PM (#3502455)
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?
Re:Javascript Best Practices by Stratoscope on Monday January 23, 2012 @06:18PM (#3502656)
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

Re:Javascript Best Practices by tikhonj on Monday January 23, 2012 @08:51PM (#3503099)
JS2-mode for Emacs[1][2] does this. It is awesome.

[1]: Original version: http://code.google.com/p/js2-mode/

[2]: Improved (IMO) fork: https://github.com/mooz/js2-mode

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.

[3]: http://www.emacswiki.org/emacs/FlymakeJavaScript#toc3

Re:Javascript Best Practices by dave1010uk on Monday January 23, 2012 @05:52PM (#3502568)
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.
Re:Javascript Best Practices by techiferous on Monday January 23, 2012 @06:20PM (#3502661)
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?
Re:Javascript Best Practices by dave1010uk on Tuesday January 24, 2012 @03:57AM (#3504018)
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.
Re:Javascript Best Practices by manojlds on Tuesday January 24, 2012 @02:51AM (#3503889)
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.
Re:Javascript Best Practices by ricardobeat on Monday January 23, 2012 @09:39PM (#3503207)
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.

https://github.com/subtleGradient/javascript-tools.tmbundle

Re:Javascript Best Practices by plf on Monday January 23, 2012 @08:39PM (#3503064)
I'm learning CoffeeScript right now, is what I write using it always valid JavaScript?
Re:Javascript Best Practices by ricardobeat on Monday January 23, 2012 @09:37PM (#3503202)
The valid CoffeeScript you write is always valid JavaScript :)
Re:Javascript Best Practices by plf on Tuesday January 24, 2012 @05:15AM (#3504157)
Can there be invalid CoffeScript?
Re:Javascript Best Practices by ricardobeat on Tuesday January 24, 2012 @05:23AM (#3504171)
of course, why not? any syntax can be broken.
Re:Javascript Best Practices by plf on Tuesday January 24, 2012 @08:01AM (#3504501)
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.
Re:Javascript Best Practices by s3b on Tuesday January 24, 2012 @01:45AM (#3503759)
I use jshint as a vim plugin.
Re:Javascript Best Practices by manojlds on Tuesday January 24, 2012 @02:48AM (#3503883)
This is way old. Hope someone doesn't start following this. Many of the points aren't even valid now.
Re:Javascript Best Practices by loftsy on Monday January 23, 2012 @04:21PM (#3502179)
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

Re:Javascript Best Practices by southern on Tuesday January 24, 2012 @05:11AM (#3504151)
Re:Javascript Best Practices by googletron on Monday January 23, 2012 @03:59PM (#3502103)
I like alot the conventions mentioned here. It would make development a lot more pleasurable.