JavaScript best-practices-for-javascript

Published on August 30th, 2013 | by Mark Ammay

0

Best Practices for JavaScript

First of all, here’s a link to Google’s JavaScript Style Guidelines that one of my bosses at work showed me.

Google JavaScript Style Guide:

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml


Now, here’s a list of best practices for JavaScript (that I started to list down before reading other ways), that I think may be useful for beginning developers as well as a resource for intermediate developers. JavaScript is very free form and allows you to develop it in many ways. Since it gives you this freedom, you must also structure it so that your code is readable, efficient and minimal.

In general, you can write your JavaScript in any way you like, however here are a few tips for you to start off with.


1) Naming Convention:

Good variable and function names should be easy to understand, short, and tell you exactly what they do. Also, start with lowercase letters and very rarely would you start a name with a capital letter.

– Should not start with a capital letter
– KISS, Keep It Simple Stupid
– Be meaningful
– Stay consistent with your naming convention


2) Defining Local Variables

Use var to define local variables, to distinguish from global variables. Also, if you don’t use var, it becomes a global variable (and becomes part of the global scope) which is something you should try to avoid.

In addition, if you have multiple variables you can declare them together instead of having several lines of code for each and every var.

Take these examples:


3) Don’t Use Inline Event Handlers

Avoid attaching JavaScript to an element, unless you don’t have a choice! Remember, it’s best to separate your JavaScript, CSS and HTML from one another, in general. Having an unobtrusive click event in your JavaScript file is better than directly attaching JavaScript to the element:


Have more to add? Comment below.

 

 


About the Author

Hey it's Mark Ammay. I'm a Web Developer with over 5 years of professional experience in the industry. I help individuals start their own website from scratch, as well as through WordPress. I'm also an Online Entrepreneur who blogs at www.MarkAmmay.com



0 comments
Back to Top ↑