tags:

views:

218

answers:

2

This is somewhat related to this question, but I'm not asking for resources about best practices in JavaScript, but your actual advise.

I'll start with my own list. You may either post an answer or directly edit the question if you're sure the advise is not controversial.

Here we go:

  • always use var
  • capitalize names of constructor functions - and nothing else
  • use === for comparison
  • use explicit casts for primitives, e.g. Number(), String(), Boolean()
  • check for primitive types with typeof
  • check for object types with instanceof
  • check for built-in object types with Object.prototype.toString() to avoid cross-frame issues, e.g.

    Object.prototype.toString.call(obj) === '[object Array]'
    
  • check this in constructors, e.g.

    function MyObject() {
        if(!(this instanceof arguments.callee))
            throw new Error('constructor called with invalid `this`');
        // [...]
    }
    
  • use anonymous functions for namespacing to not pollute the global scope, e.g.

    (function() {
        var noGlobalVar = 'foo';
        // [...]
    })();
    
  • check hasOwnProperty() in for..in loops - don't assume that no one messed with the prototypes

  • don't use for..in loops to iterate over elements of arrays or array-like objects
A: 

use explicit casts for primitives, e.g. Number(), String(), Boolean()

Really? I avoid those like the plague. What's your thinking on that?

Nosredna
my thinking was to make casts explicit, eg don't do things like `a = 3 + document.forms[0].elemens[0].value`, but `a = 3 + Number(document.forms[0].elemens[0].value)`; notice that I'm **not** advising to use wrapper objects (`new Number()`, `new String()`, ...)
Christoph
you don't need to do that unless you expect the value to contain a string like 'foo'. which will fail either way.
scunliffe
@scunliffe: ` 3 + 'foo' === '3foo' `, whereas ` 3 + Number('foo') === NaN `
Christoph
Why not use parseInt when you need something to be a number?
Annan
@Annan: that was just an example; but you're right, I don't like `parseInt()` because it'll do too much magic: ` parseInt(' 3foo') === 3 `; I believe it's better to validate user input explicitly (e.g. with regular expressions) and use functions which will cleanly fail on invalid input...
Christoph
+2  A: 

Don't meddle with core types. Never stick something onto Array.prototype -- you don't know who else is doing that, and how such things might interact.

Only check explicit types when it matters. Duck typing is a good concept.

I want to second using anonymous functions to avoid pollution of the global scope. Especially when you work a lot with jQuery, as I do, it's really helpful to use a template like this:

(function($) {
    /* Lots of code */
})(jQuery);
David