Thursday, July 19, 2012

General coding practices

While not necessarily specific to coding jQuery, I've compiled a few tips and helpful practices that may keep you a little bit saner while you're coding javascript.  None of this is required in order to make things work, but may prevent or help you debug mistakes.

Comment more than you think you need to

Whether you're in HTML or javascript, you're bound to have multiple levels of nesting going on.  As most people do, I try to keep everything indented to show the levels of nesting.  Some editors even highlight the matching close if you click on an open (I use Notepad++ for most coding) but even still it can be tricky following your end-braces, close-DIVs and such when it gets complicated.  My professors in college drilled it into our heads, most of us ignored it at the time, but they were right.  Add more comments while you're coding than you think you will need.  Coming back to it later (even a few hours later) you may not remember what a piece of code was supposed to be doing, or why you did it that way.

HTML Examples


<div id="oversimplifiedExampleDIV">
   ...Content...
</div><!-- END oversimplifiedExampleDIV -->

CSS Examples

/**** Overall Page Styles START *********/
html, body, td {margin: 0; padding: 0}
/**** Overall Page Styles END *********/

/**** Navigation Styles START *********/
#NavBar {background-color: #cc0000; color: #fff;}
/**** Navigation Styles END *********/

javascript/jQuery Examples


////////////////////////////////////////
// START Init Functions //
///////////////////////////////////////
function pageInit() {
   $(function(){
   // ... init code here
   $('a').addClass('allLinks');
   });//$ function
}// pageInit
////////////////////////////////////////
// END Init Functions //
///////////////////////////////////////

Beauty is more than skin deep

Even when you're doing your best to indent properly, sometimes it gets away from you and requires a little help to be easier to read.  There are many tools out there "beautify" your HTML and javascript code.  I use jsbeautifier.org's "Online JavaScript Beautifier" where you can paste in your HTML and/or js code, set some options and get back pretty code.  There are also standalone programs and plugins for many editors and browsers.  I prefer the online version, because it works no matter what programs or browsers you have installed.  If you're concerned about the privacy of your code (if it contains company-proprietary data for instance) you can search for "javascript beautifier" to find one that works with your tools.

No comments:

Post a Comment