Skip to content

ccheney/javascript-standards

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nerdery JavaScript Standards() {

A sensible style guide for writing JavaScript. This is a living, breathing document that will continue to evolve as new language features are unveiled.

Following these conventions will:

  • Improve readability
  • Minimize common code smells
  • Reduce errors and improve maintainability

This document is not intended to:

  • Advocate specific frameworks or libraries
  • Give advice on design patterns and project architecture
  • Guide the reader in learning JavaScript

Table of Contents

  1. Types
  2. Variables
  3. Objects
  4. Arrays
  5. Destructuring
  6. Strings
  7. Functions
  8. Arrow Functions
  9. Classes
  10. Modules
  11. Iterators and Generators
  12. Properties
  13. Comparison
  14. Comments
  15. Whitespace
  16. Commas
  17. Semicolons
  18. Naming Conventions
  19. Accessors
  20. Events
  21. DOM Interaction
  22. Asynchronous Operations
  23. Deployment
  24. License

Types

  • 1.1 The value of a variables should remain the same type as it was originally assigned (a number, string, boolean, array, or object). Avoid reassigning variables to a different type.

    // bad
    let count = 1;
    count = 'Ben Kenobi';
    
    // good
    let count = 1;
    count = 2;

  • 1.2 Values returned by functions should be of a consistent type. Avoid returning multiple different types.

    // bad
    pressYourLuck(bigMoney) {
        if (bigMoney) {
            return 'No whammies!';
        }
    
        return false;
    };

  • 1.3 Perform type coercion at the beginning of the statement.

  • 1.4 Strings:

    // this.reviewScore = 9;
    
    // bad
    const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()
    
    // bad
    const totalScore = this.reviewScore.toString(); // isn't guaranteed to return a string
    
    // good
    const totalScore = String(this.reviewScore);

  • 1.5 Numbers: Use Number for type casting and parseInt always with a radix for parsing strings. eslint: radix

    const inputValue = '4';
    
    // bad
    const val = new Number(inputValue);
    
    // bad
    const val = +inputValue;
    
    // bad
    const val = inputValue >> 0;
    
    // good
    const val = Number(inputValue);
    
    // good
    const val = parseInt(inputValue, 10);

  • 1.6 Booleans:

    const age = 0;
    
    // bad
    const hasAge = new Boolean(age);
    
    // bad
    const hasAge = !!age;
    
    // good
    const hasAge = Boolean(age);

  • 1.7 Avoid "trick" operators whose purpose is not immediately readable and obvious. If you must use a convoluted syntax for performance reasons, leave a comment explaining why and what you're doing.

    // good
    /**
     * parseInt was the reason my code was slow.
     * Bitshifting the String to coerce it to a
     * Number made it a lot faster.
     */
    const val = inputValue >> 0;

  • 1.8 When an exception is to be thrown, prefer use of one of the built-in Error types or a class that inherits from Error.

  • Why? This provide more semantic messaging and allow for the possibility of catching certain types of errors.

    divide(numerator, denominator) {
        if (denominator === 0) {
            // bad
            throw 'string exceptions are harder to handle';
    
            // good
            throw new RangeError('cannot divide by 0');
        }
    }

⬆ back to top

Variables

  • 2.1 Use const for all of your references; avoid using var. eslint: prefer-const, no-const-assign

    Why? This ensures that you can't reassign your references, which can lead to bugs and difficult to comprehend code.

    // bad
    var a = 1;
    var b = 2;
    
    // good
    const a = 1;
    const b = 2;

  • 2.2 If you must reassign references, use let instead of var. eslint: no-var jscs: disallowVar

    Why? let is block-scoped rather than function-scoped like var.

    // bad
    var count = 1;
    count += 1;
    
    // good, use the let.
    let count = 1;
    count += 1;

  • 2.3 Use one const declaration per variable. eslint: one-var jscs: disallowMultipleVarDecl

    Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a ; for a , or introducing punctuation-only diffs.

    // bad
    const items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // good
    const items = getItems();
    const goSportsTeam = true;
    const dragonball = 'z';

  • 2.4 Group all your consts and then group all your lets.

    Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.

    // bad
    let i, len, dragonball,
        items = getItems(),
        goSportsTeam = true;
    
    // bad
    let i;
    const items = getItems();
    let dragonball;
    const goSportsTeam = true;
    let len;
    
    // good
    const goSportsTeam = true;
    const items = getItems();
    let dragonball;
    let i;
    let length;

  • 2.5 Assign variables near their first use.

    Why? let and const are block scoped and not function scoped.

    // bad - unnecessary function call
    function checkName(hasName) {
        const name = getName();
    
        if (hasName === 'test') {
            return false;
        }
    
        if (name === 'test') {
            this.setName('');
            return false;
        }
    
        return name;
    }
    
    // good
    function checkName(hasName) {
        if (hasName === 'test') {
            return false;
        }
    
        const name = getName();
    
        if (name === 'test') {
            this.setName('');
            return false;
        }
    
        return name;
    }

  • 2.6 Always declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.

    // bad
    superPower = new SuperPower();
    
    // good
    const superPower = new SuperPower();

⬆ back to top

Objects

  • 3.1 Use the literal syntax for object creation. eslint: no-new-object

    // bad
    const item = new Object();
    
    // good
    const item = {};

  • 3.2 If your code will be executed in a browser context, don't use reserved words as keys. Use meaningful synonyms instead. jscs: disallowIdentifierNames

    // bad
    const superman = {
        class: 'alien',
    };
    
    // bad
    const superman = {
        klass: 'alien',
    };
    
    // good
    const superman = {
        type: 'alien',
    };

  • 3.3 Use computed property names when creating objects with dynamic property names.

    Why? They allow you to define all the properties of an object in one place.

    getKey(k) {
        return `a key named ${k}`;
    }
    
    // bad
    const obj = {
        id: 5,
        name: 'San Francisco',
    };
    obj[getKey('enabled')] = true;
    
    // good
    const obj = {
        id: 5,
        name: 'San Francisco',
        [getKey('enabled')]: true,
    };

  • 3.4 Use object method shorthand. eslint: object-shorthand jscs: requireEnhancedObjectLiterals

    // bad
    const atom = {
        value: 1,
    
        addValue: function (value) {
            return atom.value + value;
        },
    };
    
    // good
    const atom = {
        value: 1,
    
        addValue(value) {
            return atom.value + value;
        },
    };

  • 3.5 Use property value shorthand when object keys and values are redundantly named. eslint: object-shorthand jscs: requireEnhancedObjectLiterals

    // bad
    makePoint(x, y) {
        return { x: x, y: y };
    }
    
    // good
    makePoint(x, y) {
        return { x, y };
    }

  • 3.6 Group your shorthand properties at the beginning of your object declaration.

    Why? It's easier to tell which properties are using the shorthand.

    makePoint(x, y) {
        return {
            x,
            y,
            color: 'blue',
            opacity: 0.5
        };
    }

  • 3.7 Only quote properties that are invalid identifiers. eslint: quote-props jscs: disallowQuotedKeysInObjects

    Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.

    // bad
    const bad = {
        'foo': 3,
        'bar': 4,
        'data-blah': 5,
    };
    
    // good
    const good = {
        foo: 3,
        bar: 4,
        'data-blah': 5,
    };

⬆ back to top

Arrays

  • 4.1 Use the literal syntax for array creation. eslint: no-array-constructor

    // bad
    const items = new Array();
    
    // good
    const items = [];

  • 4.2 Use Array#push instead of direct assignment to add items to an array.

    const someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');

  • 4.3 Use array spreads ... or the slice() method to make a shallow copy of arrays. Avoid extraneous for loops.

    // bad
    const len = items.length;
    const itemsCopy = [];
    let i;
    
    for (i = 0; i < len; i++) {
        itemsCopy[i] = items[i];
    }
    
    // good
    const itemsCopy = items.slice()
    
    // good
    const itemsCopy = [...items];

  • 4.4 To convert an array-like object to an array, use Array#from.

    const foo = document.querySelectorAll('.foo');
    const nodes = Array.from(foo);

  • 4.5 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement. eslint: array-callback-return

    // bad
    [1, 2, 3].map(x => {
        const y = x + 1;
    });
    
    // good
    [1, 2, 3].map(x => {
        const y = x + 1;
        return x * y;
    });
    
    // good
    [1, 2, 3].map(x => x + 1);

⬆ back to top

Destructuring

  • 5.1 Use object destructuring when accessing and using multiple properties of an object. jscs: requireObjectDestructuring

    Why? Destructuring saves you from creating temporary references for those properties.

    // bad
    function getFullName(user) {
        const firstName = user.firstName;
        const lastName = user.lastName;
    
        return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName(user) {
        const { firstName, lastName } = user;
        return `${firstName} ${lastName}`;
    }
    
    // good
    function getFullName({ firstName, lastName }) {
        return `${firstName} ${lastName}`;
    }

  • 5.2 Use array destructuring. jscs: requireArrayDestructuring

    const arr = [1, 2, 3, 4];
    
    // bad
    const first = arr[0];
    const second = arr[1];
    
    // good
    const [first, second] = arr;

  • 5.3 Use object destructuring for multiple return values, not array destructuring. jscs: disallowArrayDestructuringReturn

    Why? You can add new properties over time or change the order of things without breaking call sites.

    // bad
    function processInput(input) {
        // then a miracle occurs
        return [left, right, top, bottom];
    }
    
    // the caller needs to think about the order of return data
    const [left, __, top] = processInput(input);
    
    // good
    function processInput(input) {
        // then a miracle occurs
        return { left, right, top, bottom };
    }
    
    // the caller selects only the data they need
    const { left, right } = processInput(input);

⬆ back to top

Strings

  • 6.1 Use single quotes '' for strings. eslint: quotes jscs: validateQuoteMarks

    // bad
    const name = "Capt. Janeway";
    
    // good
    const name = 'Capt. Janeway';

  • 6.2 Strings that cause the line to go over 100 characters should be written across multiple lines using string concatenation.

  • 6.3 Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion.

    // bad
    const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    
    // bad
    const errorMessage = 'This is a super long error that was thrown because \
    of Batman. When you stop to think about how Batman had anything to do \
    with this, you would get nowhere \
    fast.';
    
    // good
    const errorMessage = 'This is a super long error that was thrown because ' +
        'of Batman. When you stop to think about how Batman had anything to do ' +
        'with this, you would get nowhere fast.';

  • 6.4 When programmatically building up strings, use template strings instead of concatenation. eslint: prefer-template template-curly-spacing jscs: requireTemplateStrings

    Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.

    // bad
    sayHi(name) {
        return 'How are you, ' + name + '?';
    }
    
    // bad
    sayHi(name) {
        return ['How are you, ', name, '?'].join();
    }
    
    // good
    sayHi(name) {
        return `How are you, ${name}?`;
    }

  • 6.5 Never use eval() on a string, it opens too many vulnerabilities.

  • 6.6 Never inject untrusted strings into the DOM unless the has been sanitized. Untrusted strings include anything a user or external source can manipulate, such as query parameters, cookie values, or results from an AJAX call.

⬆ back to top

Functions

  • 7.1 Never mutate parameters. eslint: no-param-reassign

    Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.

    // bad
    foo(obj) {
      if (obj.meaningOfLife == null) {
            obj.meaningOfLife = 42;
        }
    }
    
    // good
    foo(obj) {
        let meaningOfLife = obj.meaningOfLife;
        if (meaningOfLife == null) {
            meaningOfLife = 42;
        }
    }

  • 7.2 Never reassign parameters. eslint: no-param-reassign

    Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the arguments object. It can also cause optimization issues, especially in V8.

    // bad
    foo(a) {
        a = 1;
    }

  • 7.3 Use default parameter syntax rather than mutating function parameters.

    // really bad
    signup(name) {
        // No! We shouldn't mutate function arguments.
        // Double bad: if opts is falsy it'll be set to an object which may
        // be what you want but it can introduce subtle bugs.
        name = name || 'Tony Stark';
    }
    
    // still bad
    signup (name) {
        if (name == null) {
            name = 'Tony Stark';
        }
    }
    
    // good
    signup(name = 'Tony Stark') {
        // ...
    }
    
    // good
    signup({ name = 'Tony Stark' }) {
        // ...
    }

  • 7.4 Avoid side effects with default parameters.

    Why? They are confusing to reason about.

    // bad
    count(a = b++) {
        // ...
    }

  • 7.5 Always put default parameters last.

    // bad
    signup(name = 'Tony Stark', birthdate) {
        // ...
    }
    
    // good
    signup(birthdate, name = 'Tony Stark') {
        // ...
    }

  • 7.6 Do not create functions with more than 5 parameters. When you must have that many parameters, pass in an object instead. max-params

    // bad
    signup(birthdate, address, city, state, zip, name) {
        // ...
    }
    
    // good
    signup({ birthdate, address, city, state, zip, name }) {
        // ...
    }
    
    // good
    // Pass an instance of a `UserInfo` object
    signup(userInfo) {
        // ..
    }

  • 7.7 Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.

    // bad
    nope(name, options, arguments) {
        // ...
    }
    
    // good
    yup(name, options, args) {
        // ...
    }

  • 7.8 Never use arguments, opt to use rest syntax ... instead. prefer-rest-params

    Why? ... is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like arguments.

    // bad
    concatenateAll() {
        const args = Array.prototype.slice.call(arguments);
        return args.join('');
    }
    
    // good
    concatenateAll(...args) {
        return args.join('');
    }

  • 7.9 Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint: no-loop-func

    // bad
    if (currentUser) {
        function test() {
            console.log('Nope.');
        }
    }
    
    // good
    let test;
    if (currentUser) {
        test = () => {
            console.log('Yup.');
        };
    }

  • 7.10 Never use the Function constructor to create a new function.

    Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.

    // bad
    const add = new Function('a', 'b', 'return a + b');

  • 7.11 Exit early using return statements at the beginning of the function. This avoids complex if-else blocks and unnecessary indentation.

    add(num1, num2) {
        if (num1 == null || num2 == null) {
            return false;
        }
    
        // ...
    };

  • 7.12 Add parantheses around immediately invoked function expressions. eslint: wrap-iife jscs: requireParenthesesAroundIIFE

    Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.

    // immediately-invoked function expression (IIFE)
    (function () {
        console.log('Welcome to the Internet. Please follow me.');
    }());

⬆ back to top

Arrow Functions

  • 8.1 When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint: prefer-arrow-callback, arrow-spacing jscs: requireArrowFunctions

    Why? It creates a version of the function that executes in the context of this, which is usually what you want, and is a more concise syntax.

    Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.

    // bad
    [1, 2, 3].map(function (x) {
        const y = x + 1;
        return x * y;
    });
    
    // good
    [1, 2, 3].map(x => {
        const y = x + 1;
        return x * y;
    });

  • 8.2 If your function takes a single argument, omit the parentheses. Otherwise, always include parentheses around arguments. eslint: arrow-parens jscs: disallowParenthesesAroundArrowParam

    Why? Less visual clutter.

    // bad
    [1, 2, 3].map((x) => x * x);
    
    // good
    [1, 2, 3].map(x => x * x);

⬆ back to top

Classes

  • 9.1 Always use class. Avoid manipulating prototype directly.

    Why? class syntax is more concise and easier to reason about.

    // bad
    function Queue(contents = []) {
        this.queue = [...contents];
    }
    
    Queue.prototype.queue = [];
    
    Queue.prototype.pop = function () {
        const value = this.queue[0];
        this.queue.splice(0, 1);
        return value;
    };
    
    // good
    class Queue {
        queue = [];
    
        constructor(contents = []) {
            this.queue = [...contents];
        }
    
        pop() {
            const value = this.queue[0];
            this.queue.splice(0, 1);
            return value;
        }
    }

  • 9.2 Use static for declaring class-wide properties and methods.

    // bad
    class Queue {
        constructor() {
            Queue.instanceCount++;
        }
    }
    
    Queue.instanceCount = 0;
    
    Queue.getInstanceCount = function() {
        return this.instanceCount;
    }
    
    // good
    class Queue {
      static instanceCount = 0;
    
        constructor() {
            Queue.instanceCount++;
        }
    
        static getInstanceCount() {
            return this.instanceCount;
        }
    }

  • 9.3 Use extends for inheritance.

    Why? It is a built-in way to inherit prototype functionality without breaking instanceof.

    // bad
    const inherits = require('inherits');
    function PeekableQueue(contents) {
        Queue.apply(this, contents);
    }
    inherits(PeekableQueue, Queue);
    PeekableQueue.prototype.peek = function () {
        return this.queue[0];
    }
    
    // good
    class PeekableQueue extends Queue {
        peek() {
            return this.queue[0];
        }
    }

  • 9.4 It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

    class Jedi {
        constructor(options = {}) {
            this.name = options.name || 'no name';
        }
    
        getName() {
            return this.name;
        }
    
        toString() {
            return `Jedi - ${this.getName()}`;
        }
    }

  • 9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. no-useless-constructor

    // bad
    class Jedi {
        constructor() {}
    
        getName() {
            return this.name;
        }
    }
    
    // bad
    class Rey extends Jedi {
        constructor(...args) {
            super(...args);
        }
    }
    
    // good
    class Rey extends Jedi {
        constructor(...args) {
            super(...args);
            this.name = 'Rey';
        }
    }

⬆ back to top

Modules

  • 10.1 Create a separate module for each logical set of functionality in your application. Avoid grouping multiple areas of concern or the whole application into a single file.

  • 10.2 Always use modules (import/export) over a non-standard module system. You can always transpile to your preferred module system.

    Why? Modules are the future, let's start using the future now.

    // bad
    const NerderyStyleGuide = require('./NerderyStyleGuide');
    
    // good
    import NerderyStyleGuide from './NerderyStyleGuide';

  • 10.3 Do not use wildcard imports.

    Why? This makes sure you have a single default export.

    // bad
    import * as NerderyStyleGuide from './NerderyStyleGuide';
    
    // good
    import NerderyStyleGuide from './NerderyStyleGuide';

  • 10.4 And do not export directly from an import.

    Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.

    // bad
    // filename es6.js
    export { es6 as default } from './NerderyStyleGuide';
    
    // good
    // filename es6.js
    import { es6 } from './NerderyStyleGuide';
    export default es6;

  • 10.5 Self-host third-party libraries whenever possible. Avoid loading third-party scripts from external domains and CDN's. Exceptions are libraries that do not provide self-hosted versions, such as Google Maps or Analytics.

    Why? Doing so exposes users to additional attack vectors, privacy violations (IP address tracking) and additional downtime risks.

    // bad
    import $ from 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js';
    
    // good
    import $ from './vendor/jquery.min.js';

⬆ back to top

Iterators and Generators

  • 11.1 Avoid using iterators and for-of loops. Prefer JavaScript's higher-order functions like map() and reduce(). eslint: no-iterator

    const numbers = [1, 2, 3, 4, 5];
    
    // bad
    let sum = 0;
    for (let num of numbers) {
        sum += num;
    }
    
    sum === 15;
    
    // good
    let sum = 0;
    numbers.forEach(num => sum += num);
    sum === 15;
    
    // best (use the functional force)
    const sum = numbers.reduce((total, num) => total + num, 0);
    sum === 15;

  • 11.2 Don't use generators for now.

    Why? They don't transpile well to ES5.

⬆ back to top

Properties

  • 12.1 Use dot notation when accessing properties. eslint: dot-notation jscs: requireDotNotation

    const luke = {
        jedi: true,
        age: 28,
    };
    
    // bad
    const isJedi = luke['jedi'];
    
    // good
    const isJedi = luke.jedi;

  • 12.2 Use bracket notation [] when accessing properties with a variable.

    const luke = {
        jedi: true,
        age: 28,
    };
    
    const prop = 'jedi';
    const isJedi = luke[prop];

⬆ back to top

Comparison

  • 13.1 Use === and !== over == and !=. eslint: eqeqeq

    // bad
    if (dragonball == 'z') {
        //...
    }
    
    // good
    if (dragonball === 'z') {
        //...
    }

  • 13.2 The one allowable exception is null checks. Use == and != to compare against null.

    Why? The == checks for both null and undefined in a single expression.

    // bad
    if (dragonball === null || dragonball === undefined) {
        //...
    }
    
    // good
    if (dragonball == null) {
        //...
    }

  • 13.3 Avoid the "shortcut" syntax that omits the comparison operator in most cases.

    Why? JavaScript will try to coerce the expression into a boolean value, which could lead to unintended results. Be more descriptive about what you want to compare.

    // bad
    if (name) {
        // ...
    }
    
    // good
    if (name != null) {
        // ...
    }

  • 13.4 Do use the shortcut syntax if comparing a boolean true/false value.

    // good
    let isValid = true;
    
    if (isValid) {
        // ...
    }

  • 13.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let, const, function, and class). eslint: no-case-declarations.

    Why? Lexical declarations are visible in the entire switch block but only get initialized when assigned, which only happens when its case is reached. This causes problems when multiple case clauses attempt to define the same thing.

    // bad
    switch (number) {
        case 1:
            const x = 1;
            break;
        case 2:
            const y = 2;
            break;
        default:
            const z = 3;
    }
    
    // good
    switch (number) {
        case 1: {
            const x = 1;
            break;
        }
        case 2: {
            const y = 2;
            break;
        }
        default: {
            const z = 3;
        }
    }

  • 13.6 Ternaries should not be nested and should generally be single line expressions. eslint: no-nested-ternary.

    // bad
    const foo = maybe1 > maybe2
        ? 'bar'
        : value1 > value2 ? 'baz' : null;
    
    // good
    const maybeNull = value1 > value2 ? 'baz' : null;
    
    const foo = maybe1 > maybe2 ? 'bar' : maybeNull;

⬆ back to top

Blocks

  • 14.1 Use braces with all multi-line blocks.

    // bad
    if (test)
        return false;
    
    // good
    if (test) {
        return false;
    }

  • 14.2 If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace. eslint: brace-style jscs: disallowNewlineBeforeBlockStatements

    // bad
    if (test) {
        thing1();
    }
    else {
        thing2();
    }
    
    // good
    if (test) {
        thing1();
    } else {
        thing2();
    }

⬆ back to top

Comments

  • 15.1 Use /** ... */ for multi-line comments. Include a description, specify types and values for all parameters and return values.

    // bad
    // make() returns a new element
    // based on the passed in tag name
    //
    // @method make
    // @public
    // @param {String} tag
    // @return {Element} element
    make(tag) {
        // ...
        return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed in tag name
     *
     * @method make
     * @public
     * @param {String} tag
     * @return {Element} element
     */
    make(tag) {
        // ...
        return element;
    }

  • 15.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.

    // bad
    const active = true;  // is current tab
    
    // good
    // is current tab
    const active = true;
    
    // bad
    function getType() {
        console.log('fetching type...');
        // set the default type to 'no type'
        const type = this._type || 'no type';
    
        return type;
    }
    
    // good
    function getType() {
        console.log('fetching type...');
    
        // set the default type to 'no type'
        const type = this._type || 'no type';
    
        return type;
    }
    
    // also good
    function getType() {
        // set the default type to 'no type'
        const type = this._type || 'no type';
    
        return type;
    }

  • 15.3 Prefix any comments that are meant to be revisited later with FIXME or TODO.

    Why? helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable.

  • 15.4 Use // FIXME: to annotate problems.

    class Calculator extends Abacus {
        constructor() {
            super();
    
            // FIXME: shouldn't use a global here
            total = 0;
        }
    }

  • 15.5 Use // TODO: to annotate refactoring recommendations.

    class Calculator extends Abacus {
        constructor() {
            super();
    
            // TODO: total should be configurable by an options param
            this.total = 0;
        }
    }

⬆ back to top

Whitespace

  • 16.1 Use soft tabs set to 4 spaces. eslint: indent jscs: validateIndentation

    // bad
    foo() {
    ∙∙const name;
    }
    
    // good
    foo() {
    ∙∙∙∙const name;
    }

  • 16.2 Place 1 space before the leading brace. eslint: space-before-blocks jscs: requireSpaceBeforeBlockStatements

    // bad
    function test(){
        console.log('test');
    }
    
    // good
    function test() {
        console.log('test');
    }
    
    // bad
    dog.set('attr',{
        age: '1 year',
        breed: 'Bernese Mountain Dog',
    });
    
    // good
    dog.set('attr', {
        age: '1 year',
        breed: 'Bernese Mountain Dog',
    });

  • 16.3 Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: space-after-keywords, space-before-keywords jscs: requireSpaceAfterKeywords

    // bad
    if(isJedi) {
        fight ();
    }
    
    // good
    if (isJedi) {
        fight();
    }
    
    // bad
    function fight () {
        console.log ('Swooosh!');
    }
    
    // good
    function fight() {
        console.log('Swooosh!');
    }

  • 16.5 End files with a single newline character.

    // bad
    export default class TacoTuesday {
      // ..
    }
    // bad
    export default class TacoTuesday {
        // ..
    }
    
    // good
    export default class TacoTuesday {
        // ..
    }

  • 16.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint: newline-per-chained-call no-whitespace-before-property

    // bad
    $('#items').find('.selected').highlight().end().find('.open').updateCount();
    
    // bad
    $('#items').
        find('.selected').
        highlight().
        end().
        find('.open').
        updateCount();
    
    // good
    $('#items')
        .find('.selected')
        .highlight()
        .end()
        .find('.open')
        .updateCount();
    
    // good
    const leds = stage.selectAll('.led').data(data);

  • 16.7 Leave a blank line after blocks and before the next statement. jscs: requirePaddingNewLinesAfterBlocks

    // bad
    if (foo) {
        return bar;
    }
    return baz;
    
    // good
    if (foo) {
        return bar;
    }
    
    return baz;
    
    // bad
    const obj = {
        foo() {
        },
        bar() {
        },
    };
    return obj;
    
    // good
    const obj = {
        foo() {
        },
    
        bar() {
        },
    };
    
    return obj;

  • 16.8 Do not pad your blocks with blank lines. eslint: padded-blocks jscs: disallowPaddingNewlinesInBlocks

    // bad
    function bar() {
    
      console.log(foo);
    
    }
    
    // also bad
    if (baz) {
    
        console.log(qux);
    } else {
        console.log(foo);
    
    }
    
    // good
    function bar() {
        console.log(foo);
    }
    
    // good
    if (baz) {
        console.log(qux);
    } else {
        console.log(foo);
    }

  • 16.9 Do not add spaces inside parentheses. eslint: space-in-parens jscs: disallowSpacesInsideParentheses

    // bad
    bar( foo ) {
        return foo;
    }
    
    // good
    bar(foo) {
        return foo;
    }
    
    // bad
    if ( foo ) {
        console.log(foo);
    }
    
    // good
    if (foo) {
        console.log(foo);
    }

  • 16.12 Avoid having lines of code that are longer than 100 characters (including whitespace). eslint: max-len jscs: maximumLineLength

    Why? This ensures readability and maintainability.

    // bad
    $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));
    
    // good
    const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' +
      'Whatever wizard constrains a helpful ally. The counterpart ascends!';
    
    // good
    $.ajax({
        method: 'POST',
        url: 'https://airbnb.com/',
        data: { name: 'John' },
    })
        .done(() => console.log('Congratulations!'))
        .fail(() => console.log('You have failed this city.'));

⬆ back to top

Commas

  • 17.1 Leading commas: Nope. eslint: comma-style jscs: requireCommaBeforeLineBreak

    // bad
    const story = [
        once
      , upon
      , aTime
    ];
    
    // good
    const story = [
        once,
        upon,
        aTime,
    ];
    
    // bad
    const hero = {
        firstName: 'Ada'
      , lastName: 'Lovelace'
      , birthYear: 1815
      , superPower: 'computers'
    };
    
    // good
    const hero = {
        firstName: 'Ada',
        lastName: 'Lovelace',
        birthYear: 1815,
        superPower: 'computers',
    };

  • 17.2 Additional trailing comma: Yup. eslint: comma-dangle jscs: requireTrailingComma

    Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the trailing comma problem in legacy browsers.

    // bad - git diff without trailing comma
    const hero = {
         firstName: 'Florence',
    -    lastName: 'Nightingale'
    +    lastName: 'Nightingale',
    +    inventorOf: ['coxcomb graph', 'modern nursing']
    };
    
    // good - git diff with trailing comma
    const hero = {
         firstName: 'Florence',
         lastName: 'Nightingale',
    +    inventorOf: ['coxcomb chart', 'modern nursing'],
    };
    
    // bad
    const hero = {
        firstName: 'Dana',
        lastName: 'Scully'
    };
    
    const heroes = [
        'Batman',
        'Superman'
    ];
    
    // good
    const hero = {
        firstName: 'Dana',
        lastName: 'Scully',
    };
    
    const heroes = [
        'Batman',
        'Superman',
    ];

⬆ back to top

Semicolons

  • 18.1 Yup. eslint: semi jscs: requireSemicolons

    // bad
    const name = 'Skywalker'
    return name
    
    // good
    const name = 'Skywalker';
    return name;

⬆ back to top

Naming Conventions

  • 19.1 Method names should be verbs, properties should be nouns.

    // bad
    class Wizard {
        perform = 'Smoke Rings';
    
        impressiveMagicalStuff() {
            // ...
        }
    
        scared() {
            // ...
        }
    }  
    
    // good
    class Wizard {
        ability = 'Smoke Rings';
    
        useMagic() {
            // ...
        }
    
        runAway() {
            // ...
        }
    }   

  • 19.2 If the property/method is a boolean, prefix with is, has, are, should.

    // bad
    if (visible)
        // ...
    }
    
    // good
    if (isVisible)
        // ...
    }
    
    // bad
    if (hero.superPower())
        // ...
    }
    
    // good
    if (hero.hasSuperPower())
        // ...
    }

  • 19.3 Be descriptive with your naming. Avoid single letter names unless it corresponds with the problem domain, such as i for indexes or x/y/z for coordinates.

    // bad
    q() {
        // ...
    }
    
    // good
    query() {
        // ...
    }
    
    // bad
    return { a: 0, b: 0, c: 0 };
    
    // good
    return { x: 0, y: 0, z: 0 };

  • 19.4 Use camelCase when naming objects, functions, and instances. eslint: camelcase jscs: requireCamelCaseOrUpperCaseIdentifiers

    // bad
    const OBJEcttsssss = {};
    const this_is_my_object = {};
    function c() {}
    
    // good
    const thisIsMyObject = {};
    function thisIsMyFunction() {}

  • 19.5 Use PascalCase when naming constructors or classes. eslint: new-cap jscs: requireCapitalizedConstructors

    // bad
    function user(options) {
        this.name = options.name;
    }
    
    const bad = new user({
        name: 'nope',
    });
    
    // good
    class User {
        constructor(options) {
            this.name = options.name;
        }
    }
    
    const good = new User({
        name: 'yup',
    });

  • 19.7 Don't save references to this. Use arrow functions or Function#bind. jscs: disallowNodeTypes

    // bad
    foo() {
        const self = this;
        return function () {
            console.log(self);
        };
    }
    
    // bad
    foo() {
        const that = this;
        return function () {
            console.log(that);
        };
    }
    
    // good
    foo() {
        return () => {
            console.log(this);
        };
    }

  • 19.8 If your file exports a single class, your filename should be exactly the name of the class.

    // file contents
    class CheckBox {
        // ...
    }
    export default CheckBox;
    
    // in some other file
    // bad
    import CheckBox from './checkBox';
    
    // bad
    import CheckBox from './check_box';
    
    // good
    import CheckBox from './CheckBox';

  • 19.9 Use camelCase when you export-default a function. Your filename should be identical to your function's name.

    function makeStyleGuide() {
    }
    
    export default makeStyleGuide;

  • 19.10 Use PascalCase when you export a singleton / function library / bare object.

    const NerderyStyleGuide = {
        es6: {
        }
    };
    
    export default NerderyStyleGuide;

  • 19.11 Constant values should be in all capitals and underscore-separated.

    const MAXIMUM_POWER = 9000;

  • 19.12 Group related constants in an object. All properties should be named using the same convention for constants.

    const SELECTORS = {
        ACTIVE: '.isActive',
        DISABLED: '.isDisabled',
        MODAL_CLOSE: '.js-modal-close',
     };

  • 19.13 If the values you set for constants are arbitrary and don't add meaning, use Symbol() instead.

    // bad
    const NAVIGATION = {
        HOME: 'home',
        ABOUT: 'about',
        CONTACT: 'contact', 
    }
    
    // good
    const NAVIGATION = {
        HOME: Symbol(),
        ABOUT: Symbol(),
        CONTACT: Symbol(),
    }

⬆ back to top

Accessors

  • 20.1 When getting and setting properties, use get and set accessor methods.

    //bad
    class Dragon() {
        _age = 0;
    
        getAge() {
            return this._age;
        }
    
        setAge(value) {
            this._age = value;
        }
    }
    
    const dragon = new Dragon();
    dragon.setAge(25);
    console.log(dragon.getAge()); // 25

    prefer:

    //good
    class Dragon() {
        _age = 0;
    
        get age() {
            return this._age;
        }
    
        set age(value) {
            this._age = value;
        }
    }
    
    const dragon = new Dragon();
    dragon.age = 25;
    console.log(dragon.age); // 25

  • 20.2 Getter methods should not exhibit side effects.

    //bad
    get age() {
        if (this.isBirthday()) {
            this._age++;
        }
    
        return this._age;
    }
    
    //good
    get age() {
        return this._age;
    }

⬆ back to top

Events

  • 21.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:

    // bad
    $(this).trigger('listingUpdated', listing.id);
    
    ...
    
    $(this).on('listingUpdated', (e, listingId) => {
        // do something with listingId
    });

    prefer:

    // good
    $(this).trigger('listingUpdated', { listingId: listing.id });
    
    ...
    
    $(this).on('listingUpdated', (e, data) => {
        // do something with data.listingId
    });

⬆ back to top

DOM Interaction

  • 22.2 DOM elements to be selected by JavaScript should be prefixed with js-. These selectors should not be related to any CSS styles and must exist solely for the accessing of those DOM elements.

    // bad
    <a href="#" class="previousButton">Previous</a>
    
    const $previousButton = $('.previousButton');
    
    // good
    <a href="#" class="previousButton js-previousButton">Previous</a>
    
    const $previousButton = $('.js-previousButton');

  • 22.3 If the behavior of a DOM element is tied to a JavaScript class, the selector should be named the same as that JavaScript class.

    // bad
    <div class="js-carousel"></div>
    
    new CarouselView($('.js-carousel'));
    
    // good
    <div class="js-CarouselView"></div>
    
    new CarouselView($('.js-CarouselView'));

  • 22.4 Cache jQuery lookups.

    // bad
    $('.sidebar').hide();
    $('.sidebar').css({
        'background-color': 'pink'
    });
    
    // good
    const $sidebar = $('.sidebar');
    $sidebar.hide();
    $sidebar.css({
        'background-color': 'pink'
    });

⬆ back to top

Asynchronous Operations

  • 23.1 When performing an asynchronous operation, wrap that operation with a Promise. Use a Promise implementation that conforms with the Promises/A+ spec.

    waitFor(milliseconds) {
        return new Promise((resolve, reject) => {
            window.setTimeout(
                () => { resolve(); }, milliseconds
            );
        });
    }
    
    waitFor(1000)
        .then(() => { console.log('Done waiting!'); });

  • 23.2 Avoid nesting promises several layers deep. Instead, compose a sequence of promises using a flat chain.

    //bad
    waitFor(1000)
        .then(() => {
            waitFor(2000)
                .then(() => {
                    waitFor(3000)
                        .then(() => {
                            console.log('Done waiting!');
                    });
              });
        });
    
    //good
    waitFor(1000)
        .then(() => {
            return waitFor(2000);
        })
        .then(() => {
            return waitFor(3000);
        })
        .then(() => {
            console.log('Done waiting!');
        });

  • 23.3 Always add a catch() handler to promise chains.

    Why? In some browsers, if code inside of a promise executes and generates a runtime error, it will silently fail and never be reported to the console.

    waitFor(1000)
        .then(() => { console.log('Done waiting!'); })
        .catch(exception => { console.error('Error in waitFor():', exception); });

⬆ back to top

Deployment

  • 24.1 All JavaScript deployed to a production environment must be minified and combined. Test your minified/combined code early, as it may behave differently or exhibit unforeseen JavaScript errors.

License

(The MIT License)

Copyright (c) 2014-2016 Airbnb

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

⬆ back to top

};

About

JavaScript Style Guide

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%