Thursday, April 14, 2011

JS Codings Standards

Here are some JavaScript coding standards/conventions I've been thinking about lately. I put this together pretty quickly, so it may contain some errors. What you think about these? Are there other conventions you support? Please post your feedback and/or corrections and suggestions!

////////////
// jQuery //
////////////
// 1. Name jQuery objects so that we know what they are
var $container = $("div");
///////////////
// Normal JS //
///////////////
// 1. 1 var per function
// 2. function not too long
// 3. define the length once, it's optimized
// 4. initalize vars with relevant type?
// 5. for loop over foreach. it's faster and better supported. don't care on server-side
// 6. Var stuff is all indented
// 7. Function declarations better than function expressions because of hoisting
// 8. Variables that don't get initialized (just declared) usually hang out at the bottom of the var call.
// 9. Semi-colons make it easier for me to read the flow
// 10. So does consistent tabbing
function bla(someArray) {
var hi = "",
k = [],
len = someArray.length;
i = 0,
k;
for (i = 0; i < len; i++) {
doSomethingWithI(i);
}
}
function doSomethingWithI(i) {
var x = 2;
return x * i;
}
/////////////////
// Server-side //
/////////////////
// 1. Take advantage of native-stuff wherever possible
// 2. console.log is easier than most things and takes multiple args
// 3. Don't leave in extra requires statements
Date.now(); // faster than new Date().getTime()
Array.isArray(); // better than underscore
Object.keys(); // returns the keys, yep
var arr = [1,2,3];
arr.forEach(function(val) {
console.log("Val", val);
});
////////////////
// Good Links //
////////////////
// 1. http://kangax.github.com/es5-compat-table/
// 2. https://developer.mozilla.org/en/JavaScript/Reference/
view raw standards.js hosted with ❤ by GitHub

No comments:

Post a Comment