9 ms·
Javascript Best Practices
- googletron 15y agoI like alot the conventions mentioned here. It would make development a lot more pleasurable.
- markerdmann 15y agoThis is also a great reference: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml http://google-styleguide.googlecode.com/svn/trunk/javascript...
- ckhoo 15y agoThanks for the link. Google's Javascript style guide in conjunction with this article's best practices really helped.
- funkah 15y agoCrockford'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 http://www.youtube.com/watch?v=hQVTIJBZook
- mayanksinghal 15y agoI 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.
- grannyg00se 15y agoI 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)
- googletron 15y agoyeah thats more syntax issue. alot of the time when I hate reading javascript, when it has no structure to it.
- marcins 15y agoThere's also JSHint (http://www.jshint.com/ http://www.jshint.com/), a fork of JSLint with a bit more configurability.
- dave1010uk 15y agoIt'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.
- loftsy 15y agoI'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 https://live.gnome.org/GnomeShell/Gjs_StyleGuide
- scarmig 15y agoDo 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 15y agoThe 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 15y agoI 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).
- bdg 15y ago> 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 15y agoAs 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).
- firefoxman1 15y agoYeah, 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()"
- iamds 15y agowhat is now considered good practice?
- firefoxman1 15y agoEver 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.
- Hexx 15y agoI think this just may be an old page.
- mrpollo 15y agoSurprisingly best practices dont last much on the web
- joshuahedlund 15y agoThere'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
- brunoc 15y agoPerhaps 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 15y agoIIRC 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 15y agoI had some linting tool yell at me about this recently. It said something like '''forms["formname"] better written as forms.formname'''
- locci 15y agoI 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.
- googletron 15y agowhat 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 15y agoI 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 15y agoNice. Quick off-topic question: assuming you have experience with TextMate, do you find SublimeText 2 to be slightly better than TextMate or significantly better?
- manojlds 15y agoI 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.
- dave1010uk 15y agoI 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.
- Stratoscope 15y agoI 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/ http://downloads.activestate.com/Komodo/releases/ More info: http://www.activestate.com/komodo-ide http://www.activestate.com/komodo-ide http://www.activestate.com/komodo-edit http://www.activestate.com/komodo-edit
- nailer 15y agoFor 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 http://www.w3.org/TR/html5/scripting-1.html
- ryanac 15y agoInteresting, 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 http://www.w3.org/TR/html5/semantics.html#attr-style-type
- bsimpson 15y agoUnless 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 15y agos/ghetto/standard/
- cdsanchez 15y agoI 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 15y agoCasting 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.
- VMG 15y agocareful parseFloat("08") === parseFloat("09") === 0 http://stackoverflow.com/questions/850341 http://stackoverflow.com/questions/850341
- cdsanchez 15y agoThat 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.
- VMG 15y agowhoops, got out of bed too early
- mikemaccana 15y agoOh that's neat. Thankyou.
- deleted 15y ago[deleted]
- manojlds 15y agoThis is way old. Hope someone doesn't start following this. Many of the points aren't even valid now.
- southern 15y agoAlso see http://bonsaiden.github.com/JavaScript-Garden/ http://bonsaiden.github.com/JavaScript-Garden/