Chapter 39. Coding Guidelines

Whether you're working on a project by yourself or with a group of other developers, it's very important that you follow a set of guidelines as you write code. Following guidelines promotes code quality, making it easier for you and others to find bugs, read, and maintain. The heart of most sets of guidelines is code conventions inherent to the programming language. For example, when you were introduced to variables and identifiers in Lesson 2, you were taught how identifiers should follow the code conventions already in use by the language itself.

Aside from naming identifiers, JavaScript developers follow a varying set of guidelines, usually based on conventions, to make their code easier to read and maintain. Let's look at some of them.

USE WHITESPACE

Whitespace, while not actually code, is one of the most important pieces of a programming language. It allows you to visually organize your code into readable and maintainable chunks of text. Without whitespace code would be a jumbled mess of text. Look at the following code for an example:

function doSomethingUseless(num){if(num===1){num=num+1;
doSomethingUseless(1);}
else{num=num*2;for(var i=0;i<num;i++){
num--;}
return num;
}
}

This code is difficult to read. By scanning it you can see that it's a function with some decisions and loops, but the lack of whitespace makes it difficult to discern what the code actually does. So let's add some whitespace to make it more readable:

function doSomethingUseless(num) ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.