Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active November 13, 2016 05:25
Show Gist options
  • Select an option

  • Save rstacruz/20bbdfde742f899b9c5f to your computer and use it in GitHub Desktop.

Select an option

Save rstacruz/20bbdfde742f899b9c5f to your computer and use it in GitHub Desktop.
Standard JavaScript guide

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
  • 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')
    }())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment