Skip to content

gabortill/javascipt-style-guide

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

54 Commits
 
 

Repository files navigation

JavaScript Style Guide

This is my guide for writing consistent JavaScript code.

Table of contents

  1. JSCS
  2. JS Beautifier
  3. Indention
  4. Newline
  5. Trailing whitespace
  6. Semicolon
  7. Line break
  8. Line number
  9. Quotation mark
  10. Curly brace in decision block
  11. Chaining
  12. Variable declaration
  13. Function declaration
  14. Naming
  15. Array
  16. Object
  17. Equality
  18. Built-in
  19. Comment
  20. Type Casting And Coercion
  21. Multiline string literal
  22. Module
  23. Prototype
  24. Hoisting
  25. Error handling

JSCS

Always use JSCS.

why?

JSCS is a code style linter for programmatically enforcing your style guide.

⬆ back to top

JS Beautifier

Always use JS Beautifier.

why?

To beautify your code.

⬆ back to top

Indention

  1. Use 4 spaces.
  2. Use soft TAB.

why?

  1. 4 spaces are improve readability.
  2. Use of spaces can produce a smaller file size.

⬆ back to top

Newline

Use UNIX-style newlines (\n), and a newline character as the last character of a file.

why?

Windows-style newlines (\r\n) are forbidden inside any repository.

⬆ back to top

Trailing whitespace

Clean up any trailing whitespace in javascript files.

why?

Trailing whitespaces are unnecessary and improve the file size.

⬆ back to top

Semicolon

Always use semicolons.

why?

Leave semicolons is dangerous because it can make mask errors.

⬆ back to top

Line break

  1. Limit your lines to 100 characters.
  2. Place the break after an operator, ideally after a comma. The next line should be indented more 4 spaces.

why?

  1. Screens have gotten much bigger, but your brain has not.
  2. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.

⬆ back to top

Line number

Keep max 40 lines per file.

why?

Easier to understand if you see everything without scrolling.

⬆ back to top

Quotation mark

Use single quotes.

why?

This is helpful when creating strings that include HTML.

// BAD
var bad = "BAD";
var elem = "<input type=\"text\" />";
// GOOD
var good = 'GOOD';
var elem = '<input type="text" />';

⬆ back to top

Curly brace in decision block

Always use curly braces with multiline blocks (opening braces go on the same line as the statement).

why?

To omit braces is decrease readability.

// BAD
if (true) console.log('BAD');
// BAD
if (true)
{
    console.log('BAD');
}
// GOOD
if (true) {
    console.log('GOOD');
}

⬆ back to top

Chaining

Use one method per line if you want to chain methods, and also indent these.

why?

Because it's easier to tell they are part of the same chain.

// BAD
var bad = new Bad();

bad
.methodOne()
.methodTwo()
.methodThree();
// BAD
var bad = new Bad();

bad.methodOne()
    .methodTwo()
    .methodThree();
// GOOD
var good = new Good();

good
    .methodOne()
    .methodTwo()
    .methodThree();

⬆ back to top

Variable declaration

  1. All variables should be declared before used.
  2. Avoid single var pattern and the var statements should be the first statement in the function body.

why?

  1. Use of global variables should be minimized.
  2. These are makes the program easier to read.
// BAD
var badString = 'I am BAD',
    badElem = document.getElementById('bad-elem'),
    badArr = ['one', 'two', 'three'],
    badObj = {
      'one': 1,
      'two': 2,
      'three': 3
    };
// GOOD
var goodString = 'I am GOOD';
var goodElem = document.getElementById('good-elem');
var goodArr = ['one', 'two', 'three'];
var goodObj = {
  'one': 1,
  'two': 2,
  'three': 3
};

⬆ back to top

Function declaration

  1. All functions should be declared before they are used.
  2. Inner functions should follow the var statement.

why?

  1. Use of global functions should be minimized.
  2. This helps make it clear what variables are included in its scope.

⬆ back to top

Naming

  1. Do not use reserved words.
  2. Use descriptive lowerCamelCase naming for variables, properties and functions except constructor functions.
  3. Constructor functions that must be used with the new prefix and UpperCamelCase naming.

why?

  1. Some identifiers are reserved words and cannot be used as variables or function names.
  2. For easier understanding.
  3. Bad things can happen if new is not used, so the capitalization convention is the only defense we have.
// BAD
var badname = 'I am BAD';
// BAD
var bad_name = 'underbar is BAD';
// BAD
var BADNAME = 'There is no constants in ECMAScript 5';
// BAD
var a = 'avoid single character names';
// GOOD
var goodName = 'I am GOOD';

⬆ back to top

Array

Use Array literals instead of constructors.

why?

Array constructors are error-prone due to their arguments.

// BAD
var badArr = new Array();
// GOOD
var goodArr = [];

Single line Array initializer – no space after [ and before ].

// BAD
var badArr = [ 'one', 'two', 'three' ];
// GOOD
var goodArr = ['one', 'two', 'three'];
// multiline array initializer is BETTER
var goodArr = [
    'one',
    'two',
    'three'
];

Never use Array as a map/hash/associative array.

why?

There is no associative arrays in javascript.

// BAD
var skills = [];
skills['Document language'] = 'HTML5';
var skills = {
    'Document language': 'HTML5'
};

⬆ back to top

Object

Use literal syntax for object creation.

why?

They don't have the constructor problem like Arrays, but be consistent.

// BAD
var badObj = new Object();
// GOOD
var goodObj = {};

Single line Object initializer – no space after { and before }.

// BAD
var badObj = { a: 0, b: 1, c: 2 };
// GOOD
var goodObj = {a: 0, b: 1, c: 2};
// multiline object initializer is BETTER
var goodObj = {
    a: 0,
    b: 1,
    c: 2
};

Do not align to the colon.

// BAD
var badObj = {
    bottom : 15,
    left   : 15,
    right  : 20,
    top    : 110
};
// GOOD
var goodObj = {
    bottom: 15,
    left: 15,
    right: 20,
    top: 110
};

⬆ back to top

Equality

Use === and !== operators.

why?

The == and != operators do type coercion before comparing.

⬆ back to top

Built-in

Never extend the prototype of native JavaScript objects unless polyfilling.

why?

Hard to debug, and your future self will be forever grateful.

// BAD
Array.prototype.empty = function () {
    return !this.length;
};

var badArr = [];
if (badArr.empty()) {
    console.log('I am BAD');
}
// GOOD
var goodArr = [];

if (!goodArr.length) {
    console.log('I am GOOD');
}

⬆ back to top

Comment

  1. Generally use single line comments.
  2. Place single line comments on a newline of subject and put an empty line before.

why?

  1. Save block comments for formal documentation.
  2. Empty lines above comments are improve readability.
// BAD
var bad = true; // comment in wrong place
// BAD
var bad;
// missing empty newline
bad = true;
// BAD
/*
block comments
for documentation
*/
var bad = true;
// GOOD
var good;

// set to true
good = true;

⬆ back to top

Type Casting And Coercion

Use parseInt() for Numbers and always with the radix parameter.

why?

ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

// BAD
var badSize = parseInt('16px');
// GOOD
var goodSize = parseInt('16px', 10);

Use Boolean() for Booleans without the new operator.

why?

The result with the new operator will be an Object (complex type), but without it will be a primitive type.

// BAD
var badBool = new Boolean(something);
// GOOD
var goodBool = Boolean(something);

⬆ back to top

Multiline string literal

Not use multiline string literals. Use string concatenation instead.

why?

The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.

// BAD
var badStr = 'Veggies es bonus vobis, proinde vos postulo essum magis \
                 kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon \
                 azuki bean garlic';
// GOOD
var goodStr = 'Veggies es bonus vobis, proinde vos postulo essum magis' +
    'kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon' +
    'azuki bean garlic';

⬆ back to top

Module

  1. Start modules with an Immediately Invoked Function Expression.
  2. Use strict mode.

why?

  1. In order to avoid global namespace pollution.
  2. Strict mode enables more warnings and makes JavaScript a cleaner language.
// BAD
var badModule = 'I want to be part of a module';
// GOOD
(function () {
    'use strict';

    var goodModule = 'IIFE is cool';
}());

⬆ back to top

Prototype

Assign methods to the prototype object, instead of overwriting the prototype with a new object.

why?

Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base.

// BAD
BadObj.prototype = {
    badProp: 'I am bad',
    badMethod: function () {
        return 'bad';
    }
};
// GOOD
GoodObj.prototype.goodProp = 'I am good';
GoodObj.prototype.goodMethod = function () {
    return 'good';
};

⬆ back to top

Hoisting

Moving declarations to the top.

why?

Otherwise it cause an error, improve readability and easier to understand the code.

// BAD
function badWrapper () {
    console.log(msg);

    var msg = 'I am bad';
}
// GOOD
function goodWrapper () {
    var msg = 'I am happy';

    console.log(msg);
}

⬆ back to top

Error handling

Try to use Exceptions

// GOOD
try {
    throw new Error('Whoops!');
} catch (e) {
    console.log(e.name + ': ' + e.message);
}

⬆ back to top

About

This is my guide for writing consistent JavaScript code.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published