An explanation of the JavaScript Standard Style
Pull request Compare This branch is 2 commits behind rstacruz:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
README.md

README.md

Standard JavaScript

This is a TL;DR of the standard and semistandard JavaScript rules. For more detailed explanations, see standard's rules documentation.

js-standard-style js-semistandard-style

Rules

  • Use 2 spaces for indentation.

    function hello (name) {
      console.log('hi', name)
    }
  • Use single quotes for strings except to avoid escaping.

    console.log('hello there')
    $("<div class='box'>")
  • No unused variables.

    function myFunction () {
      var result = something()   // ✗ avoid
    }
  • Add a space after keywords.

    if (condition) { ... }   // ✓ ok
    if(condition) { ... }    // ✗ avoid
  • Add a space after function names.

    function name (arg) { ... }   // ✓ ok
    function name(arg) { ... }    // ✗ avoid
    
    run(function () { ... })      // ✓ ok
    run(function() { ... })       // ✗ avoid
  • Always use === instead of ==.
    Exception: obj == null is allowed to check for null || undefined.

    if (name === 'John')   // ✓ ok
    if (name == 'John')    // ✗ avoid
    if (name !== 'John')   // ✓ ok
    if (name != 'John')    // ✗ avoid
  • Infix operators must be spaced.

    // ✓ ok
    var x = 2;
    var message = 'hello, ' + name + '!';
    // ✗ avoid
    var x=2;
    var message = 'hello, '+name+'!';
  • Commas should have a space after it.

    // ✓ ok
    var list = [1, 2, 3, 4];
    function greet (name, options) { ... }
    // ✗ avoid
    var list = [1,2,3,4];
    function greet (name,options) { ... }
  • Keep else statements in the same line as its curly braces.

    // ✓ ok
    if (condition) {
      // ...
    } else {
      // ...
    }
    // ✗ avoid
    if (condition) {
      // ...
    }
    else {
      // ...
    }
  • For multi-line if statements, use curly braces.

    // ✓ ok
    if (options.quiet !== true) console.log('done')
    // ✓ ok
    if (options.quiet !== true) {
      console.log('done')
    }
    // ✗ avoid
    if (options.quiet !== true)
      console.log('done')
  • Always handle the err function parameter.

    // ✓ ok
    run(function (err) {
      if (err) throw err
      window.alert('done')
    })
    
    // ✗ avoid
    run(function (err) {
      window.alert('done')
    })
  • Always prefix browser globals with window..
    Exceptions are: document, console and navigator.

    window.alert('hi')   // ✓ ok

Semicolons

These rules are enforced for standard, but are not imposed in semistandard.

  • No semicolons. (see: 1, 2, 3)

    window.alert('hi')   // ✓ ok
    window.alert('hi');  // ✗ avoid
  • Never start a line with ( or [. This is the only gotcha with omitting semicolons. (see: 1)

    ;(function () {
      window.alert('ok')
    }())