Let's write better JavaScript, and the same, k?
We always use spaces, and we always use four. Set your editor now.
function myFunction() {
// Indented using 4 spaces (not a \t tab!)
return "correct!";
}
Variable names should:
-
Be as short as possible, without being unclear
-
Be as clear as possible, without being too long
-
Avoid abbreviations
-
Be written in camelCase
// Use this format (camelCase) var myAwesomeVariable; // Not these var my-awesome-variable; // syntax error var my_awesome_variable; var MyAwesomeVariable; // only for 'class' names
-
Differentiated from the left
// These are not so easy to tell apart var codeStandardsDocumentJs = {}; var codeStandardsDocumentCss = []; // This is better var jsCodeStandardsDocument = {}; var cssCodeStandardsDocument = [];
-
Prefer nested objects over long names
// Create nested objects for organization var urlGetters = { small: function () { }, big: function () { } }; // Instead of really long, cumbersome variable names var smallUrlGetter = function () { }; var bigUrlGetter = function () { };
Write moar comments. We minify.
// Use this single line style for helpful explanations.
/**
* Use this docblock style for documentation and stuff
*
* @tagName some value
*/
JS scoping is crazy, so declare all your variables for any scope at the top of that scope.
function myScope() {
var counter,
element,
galleryObject;
// Do function-y stuff
return galleryObject;
}
Put a space around everything, as a general rule. PUT A SPACE AROUND IT.
A few exceptions:
-
A named function and its opening paren
function namedFunction() { // no space between function name and parens
-
Unary increment/decrement operators
i++; // no space --j; // still no space, see?
-
The left side of a comma
myFunction( parameter1, parameter2 ); // I shouldn't have to tell you this
Everything else should be separated by spaces, including the following:
-
Parameters inside of parens
var gallery = new GKGallery( options ); // do this var gallery = new GKGallery(options); // don't do this, it's gross
-
Anonymous functions (don't make an incompetent person think the function is named 'function')
var iife = (function () { // keep the space between 'function' and '()' for clarity // do all that sweet closure stuff }());
-
Control statements and their parens, and before every opening bracket "{"
if(something){ // DON'T MASH IT ALL TOGETHER } if ( something ) { // pretty! }
You get the point.
Still have more to do, but this is a good start