JavaScript recommendations

This is somewhat related to this question , but I am not asking for resources on best practices in JavaScript, but your actual advice.

I will start with my own list. You can either post the answer or directly edit the question if you are sure that the advice is not inconsistent.

Here we go:

  • always use var
  • uppercase constructor function names - and nothing more
  • use ===for comparison
  • use explicit casts for primitives, for example. Number(), String(),Boolean()
  • check primitive types with typeof
  • check object types with instanceof
  • check the built-in types of objects with Object.prototype.toString()to avoid problems with multiple frames, for example

    Object.prototype.toString.call(obj) === '[object Array]'
    
  • this ,

    function MyObject() {
        if(!(this instanceof arguments.callee))
            throw new Error('constructor called with invalid `this`');
        // [...]
    }
    
  • , ,

    (function() {
        var noGlobalVar = 'foo';
        // [...]
    })();
    
  • hasOwnProperty() for..in - ,

  • for..in , .
+5
4

. - Array.prototype - , , .

, . - .

, . , jQuery, , , :

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

, . Number(), String(), Boolean()

? , . ?

0

:

, . , , break continue , if.

0

jslint.

, .

Jslint will tell you if you break one or more "best practices."

Also consider using an IDE that supports jslint. I can recommend WebStorm or Sublime Text 2 (I tested these 2 myself, and they support jslint very well).

0
source

All Articles