arozwalak
7/2/2015 - 12:16 PM

Javascript: Best practices

Javascript: Best practices

  • All-caps for global variables ie. MYVAR or MY_VAR
  • All-caps for "constants" ie. MAX_WIDTH, PI = 3.14
  • Underscore inf front for private method or property
var person = {
  getName: function () {
    return this._getFirst() + ' ' + this._getLast();
  },
  _getFirst: function () {
    // ...
  },
  _getLast: function () {
    // ...
  }
};
  • Using a single var statement at the top of your functions
  • Initialize the variable with an initial value at the time you declare it
  • for loop
var i, myarray = [];
for (i = myarray.length; i -= 1) {
    // do something with myarray[i]
}

var myarray = [],
    i = myarray.length;
while (i--) {
    // do something with myarray[i]
}
  • for-in loops (enumeration) [nonarray objects]
  • the order of listing the properties is not guaranteed in a for-in loop.
  • use method hasOwnProperty() when iterating over object properties to filter out properties that come down the prototype chain.
for (var i in object) {
    if (object.hasOwnProperty(i)) {
          console.log(i, ": ", object(i));
     }
}

hasOwnProperty()

for (var i in man) {
  if (Object.prototype.hasOwnProperty.call(man, i)) { //filter
    console.log(i, ":", man[i]);
  }
}

var i,
  hasOwn = Object.prototype.hasOwnProperty;

for(i in man) {
  if (hasOwn.call(man, i)) {
    console.log(i, ":", man[i]);
  }
}

var i,
  hasOwn = Object.prototype.hasOwnProperty;
  
for (i in man) if (hasOwn.call(man, i) {
  console.log(i, ":", man[i]);
}

###(Not) Augmenting Built-in Prototypes

Augment built-in prototypes only when all these conditions are met:

  1. It's expected that future ECMAScript versions or JavaScript implementations will implement this functionality as a built-in method consistently.
  2. You check if your custom property or method doesn't exist already.
  3. You clearly document and communicate the change with the team.
if (typeof Object.prototype.myMethod !== "function") {
  Object.prototype.myMethod = function () {
    // implementation...
  };
}

switch Pattern

var inspect_me = 0,
  result = '';
  
switch (inspect_me) {
case 0:
  result = "zero";
  break;
case 1:
  result = "one";
  break;
default:
  result = "unknown";
}

Number Conversions with parseInt()

var month = "06",
  year = "09";
  
month = parseInt(month, 10);
year = parseInt(year, 10);

+"08" // result is 8
Number("08") // 8

parseInt("08 hello") // 8
+"08" // NaN
Number("08") // NaN