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()
infor..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