ProgClub standard JavaScript format
OK, so if there's such a thing as the ProgClub standard JavaScript format I'd better explain what that is... this page remains a work in progress. The purpose of this guide is to inform the ProgClub.js project.
Always use curly brackets even when not required:
if ( true ) { return foo(); } // not: if ( true ) return foo();
All on one line if only one short statement:
if ( true ) { return false; } // not: if ( true ) { return false; }
Multiple lines if an if-block is followed by else/else-if:
if ( true ) { return false; } else { return true; } // not: if ( true ) { return false; } else { return true; }
Multiple lines if more than one statement:
if ( true ) { foo(); bar(); } // not: if ( true ) { foo(); bar(); }
Open curly bracket on same line, close curly bracket on new line:
function test() { return true; }
Always use a semicolon if you can!
Try to keep line-length less than 78 characters (not a hard rule).
New lines before comments:
if ( true ) { // first group of functions: f1(); f2(); f3(); // next group of functions (blank line above): f4(); f5(); }
Prefer // comments to /**/ (not a hard rule). If as a rule you don't use /**/ comments then you can use them temporarily if you need to comment out a bunch of code. If you were using /**/ comments you might not be able to do that because a stray */ would terminate your comment prematurely (/**/ comments don't nest!) I'm still thinking about whether I want to automatically reformat /**/ comments as // comments.
Generally space after open bracket and space before close bracket:
function fn( arg_1, arg_2, arg_3 ) { return arg_1 + arg_2 + arg_3; } // including: ( function( arg ) { window.arg = arg; } )(); // and: $.on( 'click', function( e ) { alert( e.whatever ); } );
Multiple lines for:
function whatever( my_long_argument_for_my_whatever_function, and_another_long_argument_for_my_function ) { return happiness; } // and: function yeah() { return my_really_long_value + " some string that I'm adding " + your_happiness; }
No blanks between closing curly brackets (except for single-line):
function fn( a, b, c ) { if ( a ) { while ( b() ) { c++; } } } // not: function fn( a, b, c ) { if ( a ) { while ( b() ) { c++; } } }