Skip to content

Code Formatting JavaScript

Adroaldo de Andrade edited this page Sep 29, 2014 · 2 revisions

JavaScript Code Formatting

  • Do not use tabs, use four spaces instead
  • Indentation should have 4 spaces
  • Break line when it has 80 characters wide
  • Do not leave space at end of line
  • At end of file leave a new line
  • Comments and coding should be written on English

Spaces

  1. Always add space between declaration, operation and value
  2. Shoud have space after comma, but not before it
  3. Arguments should have no spaces between name and paretheses
  4. Use space between function and its parenthesis and parentheses and curly braces
  5. After keywords (for, while, if, functions...) should have space
  6. Should use NO SPACE
    1. Inside curly braces, brackets or parentheses and its contents (between elements is imperative)
    2. Between names and its arguments on function calls

Good

var fileTypes = ['.html', '.js', '.py'];
var sum = a + b;
sum += 1;
var mean = sum / 3;

Bad

var fileTypes = [ '.html','.js','.py' ];
var sum=a+b;
sum+=1;
var mean=sum/3;

Curly Braces

  1. Should be used even if they are not necessary
  2. Curly braces should start on same declaration line

Good

if (obj.prop) {
    obj.doSomething();
}

Bad

if (obj.prop)
    obj.doSomething();

Variables and Constants

  1. Variables should start with lower case
  2. Always use camelCase on long names
  3. Constants should be upper cased with underscore between words
  4. Strings should use single quotes
  5. Always insert semicolon at end of declarations

Good

var dayOfWeek = 'Monday';
var SECONDS_PER_MINUTE = 60;
var weekDays = [0, 1, 2, 3, 4, 5, 6];
var months = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'oct', 'Nov', 'Dec'};

Bad

var day_of_week = "Monday"
var secondsPerMinuteConstant = 60
var weekDays = [ 0,1,2,3,4,5,6 ];
var months = { 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','oct','Nov','Dec' };

Functions and Classes

  1. Always use camelCase on long names
  2. Functions should start with lower case
  3. "Classes" should start with capitalized letter
  4. Add space between function name and its arguments`
  5. Colon on object property and functions should have no space before but space after

Good

var Person = function (name) {
    this.name: name,

    this.setName: function (name) {
        this.name = name;
    },

    this.getName: function (name) {
        return this.name;
    }
}

var voidFunction = function () {
    return;
}

voidFunction();

Bad

var person = function( name )
{
    this.name:name,
    this.setName:function ( name ) {
        this.name=name;
    },
    this.getName: function (name) {
        return this.name;
    }
}

var voidFunction = function( )
{
    return;
}

voidFunction ( );
  1. Add new line before a block of code, except first line block`
var isPrime = function (num) {
    var square = (int) Math.sqrt(num);

    if (num < 2) {
        return false;
    }

    for (var i = 2; i <= square; i++) {
        if ((num % i) === 0) {
            return false;
        }
    }

    return true;
}

Code Blocks

Case within a switch should end with break, throw or return except on default. If is need a fall-through it should be written as an explicit comment

Good

switch (val) {
    case 1:
        doSomething();
        //fall-through
    case 2:
        doSomethingElse();
        break;
    default:
        doNothing():
}

Bad

switch (val) {
    case 1:
        doSomething();
    case 2:
        doSomethingElse();
        break;
    default:
        doNothing();
}

Comments

  • Are to facilitate code understanding
  • Explain non-obvious decisions
  • Inform function preconditions and results
  • It should be succinct and direct with no obviousness
  • Should stay togather with its code reference and changed when its code were refactored
  • Should be in JavaDoc style
/**
 * Comentário sobre funcionalidade de função
 * @param val valor a ser impresso na tela
 */
var print = function (val) {
    console.log(val);
}
  • Use tags for automatic generation
@constructor
@interface
@implements
@override
@param
@private
@protected
@public
@return
@see
  • Use HTML when necessary
/**
 * Calcula fator baseado em três
 * elementos:
 * <ul>
 * <li>itens enviados</li>
 * <li>itens recebidos</li>
 * <li>ultima data registrada</li>
 * </ul>
 */

Clone this wiki locally