Better Javascript

Loop
1.

for (i = 0, max = myarray.length; i < max; i++) { 

2.

Count down to 0, is usually faster
it’s more efficient to compare to 0 than to the length of the array or to anything other than 0

For loop

for (i = myarray.length; i--;) {  

While loop

    i = myarray.length;  
while (i--) {  

For in / hasOwnProperty

Adding method to all objs

// somewhere else in the code  
// a method was added to all objects  
if (typeof Object.prototype.clone === "undefined") {  
   Object.prototype.clone = function () {};  
}  

Filter hasOwnProperty

// 1.  
// for-in loop  
for (var i in man) {  
   if (man.hasOwnProperty(i)) { // filter  
      console.log(i, ":", man[i]);  
   }  
}  
/* result in the console 
hands : 2 
legs : 2 
heads : 1 
*/  
// 2.  
// antipattern:  
// for-in loop without checking hasOwnProperty()  
for (var i in man) {  
   console.log(i, ":", man[i]);  
}  
/* 
result in the console 
hands : 2 
legs : 2 
heads : 1 
clone: function() 
*/  

Another pattern to filter

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

Or
1.

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

2.

// Warning: doesn't pass JSLint  
var i, hasOwn = Object.prototype.hasOwnProperty;  
for (i in man) if (hasOwn.call(man, i)) { // filter  
    console.log(i, ":", man[i]);  
} 

eval()

// antipattern  
var property = "name";  
alert(eval("obj." + property));  
  
// preferred  
var property = "name";  
alert(obj[property]);  

same as setTimeOut(), setInterval()

// antipatterns  
setTimeout("myFunc()", 1000);  
setTimeout("myFunc(1, 2, 3)", 1000);  
  
// preferred  
setTimeout(myFunc, 1000);  
setTimeout(function () {  
   myFunc(1, 2, 3);  
}, 1000);  

Here only un remains as a global variable polluting the namespace

console.log(typeof un); // "undefined"  
console.log(typeof deux); // "undefined"  
console.log(typeof trois); // "undefined"  
  
var jsstring = "var un = 1; console.log(un);";  
eval(jsstring); // logs "1"  
  
jsstring = "var deux = 2; console.log(deux);";  
new Function(jsstring)(); // logs "2"  
  
jsstring = "var trois = 3; console.log(trois);";  
(function () {  
   eval(jsstring);  
}()); // logs "3"  
  
console.log(typeof un); // number  
console.log(typeof deux); // undefined  
console.log(typeof trois); // undefined  

eval() can access and modify a variable in its outer scope, whereas Function cannot

(function () {  
   var local = 1;  
   eval("local = 3; console.log(local)"); // logs 3  
   console.log(local); // logs 3  
}());  
  
(function () {  
   var local = 1;  
   Function("console.log(typeof local);")(); // logs undefined  
}());  

string to number
Prevent octal confusion

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

Alternate string to number

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

Code convention
Naming globals with all caps can reinforce the practice of minimizing their number and can make them easily distinguishable.

// precious constants, please don't touch  
var PI = 3.14,  
    MAX_WIDTH = 800; 

private with _

var person = {  
    getName: function () {  
        return this._getFirst() + ' ' + this._getLast();  
    },  
  
    _getFirst: function () {  
        // ...  
    },  
    _getLast: function () {  
        // ...  
    }  
};  

Other conventions :

  • private_ : name_, getElements_()
  • _protected properties, __private properties
  • In Firefox some internal properties not technically part of the language are available, and they are named with a two underscores prefix and a two underscore suffix, such as __proto__ and __parent__

ref : tutsplus

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s