Top

JavaScript coding standards we follow

This document’s primary motivation is twofold:

1) code consistency
2) best practices.

By maintaining consistency in coding styles and conventions, we can ease the burden of legacy code maintenance, and mitigate risk of breakage in the future. By adhering to best practices, we ensure optimized page loading, performance and maintainable code. Therefore, at Innofied, we follow these guidelines strictly while programming.

1 . Proper File Naming Conventions

a) Use Constructor function name as file names. So as per example, file name will be Hero.js

For example:

function Hero() {
  this.occupation = ‘Ninja’;
}

b) Choose meaningful file names for your JavaScript files like the file names should be derived or chosen by focusing on what the file holds and use CamelCase for your file names.

2 . Indentation

a) The unit of indentation is 4 spaces.
b) Use of tabs should be avoided.
c) Use “format” option of your IDE.

3 . Line Length

a) Avoid line length more than 80 characters.

4 . Proper Comments

a) It is important that comments be kept up-to-date.
b) Make comments meaningful.

5. Variable Declarations

a) All variable should be declared before use.
b) The ‘var’ statement should be the first statement in function body.
c) It is preferred that each variable be given its own line & comment.

For example:

var currentEntry; // currently selected table entry
var level; // indentation level
var size; // size of table

d) Use of global variables should be minimised.
e) Implied global variables should never be used.

6 . Function Declarations

a) All functions used should be declared before use.
b) There should be no space between the name of the function and the ( (left parenthesis of its parameter list. There should be 1 space between the ) (right parenthesis) and the { (left curly brace) that begins the statement body. The right } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.

For example:

function outer(a, b) {
  var e = c * d;

  function inner(a, b) {
    return (e * a) + b;
  }
  return inner(0, 1);
}

7 . Variable Names

a) Names should be formed from the 26 upper and lower case letters(A .. Z, a .. z), the 10
digits (0 .. 9), and _(underbar).
b) Avoid use of international characters.
c) Do not use $(dollar sign) or (backslash).
d) Do not use _(underbar) as the first character of a name.

8 . Use === Instead of ==

a) JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

9 . eval is Evil

a) The eval function is the most misused feature of JavaScript. Avoid it.
b) eval has aliases. Do not use the ‘Function’ constructor. Do not pass strings to ‘setTimeout’ or ‘setInterval’. Instead pass a function name.

For example:
Bad:

setInterval("document.getElementById('container').innerHTML += 'My
new number: ' + i", 3000);

Better:

setInterval(someFunction, 3000);

10 . Don’t use short-hand ever

Technically, you can get away with omitting most curly braces and semicolons. Most browsers will correctly interpret the following:

if (someVariableExists)
  x = false
anotherFunctionCall();

One might think that the code above would be equivalent to:

if (someVariableExists) {
  x = false;
  anotherFunctionCall();
}

Unfortunately, he’d be wrong. In reality, it means:

if (someVariableExists) {
  x = false;
}
anotherFunctionCall();

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs.

11 . Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

12 . Place scripts at the bottom of your page

The primary goal is to make the page load as quickly as possible for the user.

13 . The fastest way to build your string

Don’t always reach for your handy-dandy “for” statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.
For example:

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

14 . Don’t use the ‘with’ statement

At first glance, “With” statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects.
For example:

with(being.person.man.bodyparts) {
  arms = true;
  legs = true;
}

Unfortunately, after some testing, it was found that they “behave very badly when setting new members.” Instead, you should use var.

For example:

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

15 . Use {} intead of new object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the “new” constructor.

For example:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function () {
  console.log(this.name);
}

However, this method receives the “bad practice” stamp without actually being so. Instead, it is
recommend that you use the much more robust object literal method.

For example:

var o = {
  name: 'Jeffrey',
  lastName = 'Way',
  someFunction: function () {
    console.log(this.name);
  }
};

16 . Use [] instead of new Array()

The same applies for creating an array.

For example:
Okay:

var a = new array();
a[0] = ‘joe’;
a[1] = ‘plumber’;

Better:

var a = [‘joe’, ‘plumber’];

17 . Long list of variables? Omit the ‘var’ keyword and use commas instead

For example:
Okay:

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

Better:

var someItem = 'some string',
anotherItem = 'another string',
oneMoreItem = 'one more string';

18 . Always use semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

For example:

var someItem = 'some string'

  function doSomething() {
    return 'something'
  }

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.
Better:

var someItem = 'some string';

function doSomething() {
  return 'something';
}

19 . Remove ‘language’ Attribute

Years ago, it wasn’t uncommon to find the “language” attribute within script tags.
For Example:

<script type="text/javascript" language="javascript">...</script>

However, this attribute has long since been deprecated; so leave it out.

Swarnendu De

Swarnendu is the Co-founder and Lead architect at Innofied. For the last seven years, he has been working with numerous JavaScript technologies including Backbone.js, Node.js, ExtJS, Sencha, and so on, and has developed more than 50 complex JavaScript-based applications thus far. He is the author of the book Backbone.js Patterns and Best Practices. Swarnendu regularly writes at his personal blog, Innofied Blog, the Tuts+ network, and provides support and assistance for JavaScript, Sencha and much more around the web. You can reach him through his website at http://www.swarnendude.com or via Twitter at @swarnendude