Maintainable Javascript – Part 1

As we are now writting more and more javascript code. It is very important that we write mantainable code.
I have recently came across a book Mantaintable Javascript, and wanted to share some of the code snippets from the book. The book describes some best practices and conventions used in Javascripts

This part is releated to naming conventions.

Line Breaking:

// Good: Break after operator, following line indented two levels
callAFunction(document, element, window, "some string value", true, 123,
navigator);
// Bad: Following line indented only one level
callAFunction(document, element, window, "some string value", true, 123,
navigator);
// Bad: Break before operator
callAFunction(document, element, window, "some string value", true, 123
, navigator);

Variables and Functions:
The good practice is to have functions names starts with verbs.

// Good
var count = 10;
var myName = "Nicholas";
var found = true;
// Bad: Easily confused with functions
var getCount = 10;
var isFound = true;
// Good
function getName() {
return myName;
}
// Bad: Easily confused with variable
function theName() {
return myName;
}

Constants:
Use uppercase for contstant just like C and C++.

var MAX_COUNT = 10;
var URL = "http://www.nczonline.net/";

Related Links:
Google style guide for javascript

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s