O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required