= JavaScript Notes & Best Practices = These are a few notes and best practices for doing client-side development with Javascript. === Use a JavaScript Library === First and foremost, you'll almost certainly want to use a JavaScript library. Like CSS, JavaScript isn't entirely cross-browser compatible, and there are a number of things that are harder to do than they should be. A JS library eases your pain on both these fronts, while (typically) adding very little overhead. My favorite library is [[http://jquery.com/|jQuery]]. [[http://developer.yahoo.com/yui/|YUI]] is also pretty good, albeit a little heavier. === Namespace Your Code === You'll probably want to put all of your JS code in a namespace. See [[Namespacing and Aliasing Namespaces In Javascript]] === Return null, not false === Since JavaScript supports ''null'', you should always use that instead of ''false'' to return a 'no data found' indication in a function. There is a temptation to return ''dataValue'' or ''false'', but ''false'' should be reserved for functions that return //only// true or false. ''dataValue'' or ''null'' is more correct. This is no different than any other language, but is still a mistake that is easy to make. === Using Optional Parameters & Default Arguments === If you need to create a function with optional parameters and defaults for those parameters that aren't specified, see [[Optional Parameters & Default Arguments]]. === Using Classes & the 'this' keyword === Since classes are [[Basic JavaScript#classes|currently so bastardized]] in Javascript, I generally tend to avoid them, and not program in an object oriented fashion. That also lets me avoid using the ''this'' keyword, because I'm not instantiating objects. The context of ''this'' can change fairly easily, especially if you're working with someone else's framework (e.g. [[http://developer.yahoo.com/yui/|YUI]]), and is an easy source for frustration or errors. That said, there are some cases when creating a class really is the best option for managing data. No harm in doing that, and we can look forward to a better implementation in JS 2.0. === Unobtrusive Javascript === If possible, it is a good idea to write 'unobtrusive javascript', which is separate from both the content layer (HTML/DOM) and the presentation layer (CSS). The idea (ideally) is to have absolutely none of your JavaScript code embedded in your HTML markup; you include a ''