Skip to content

thenerdery/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

ESLint Config for the Nerdery JavaScript Standards

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 A variable should remain the same type 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, no-implicit-coercion

    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

    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

    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 dragonball,
        items = getItems(),
        goSportsTeam = true;
    
    // bad
    const items = getItems();
    let dragonball;
    const goSportsTeam = true;
    
    // good
    const goSportsTeam = true;
    const items = getItems();
    let dragonball;

  • 2.5 Assign variables near their first use.

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

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

  • 2.6 Always use const or let to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: no-undef

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

  • 2.7 Don't chain variable assignments. eslint: no-multi-assign

    Why? Chaining variable assignments creates implicit global variables.

    // bad
    (function example() {
        // JavaScript interprets this as
        // let a = ( b = ( c = 1 ) );
        // The let keyword only applies to variable a; variables b and c become
        // global variables.
      let a = b = c = 1;
    }());
    
    console.log(a); // undefined
    console.log(b); // 1
    console.log(c); // 1
    
    // good
    (function example() {
        let a = 1;
        let b = a;
        let c = a;
    }());
    
    console.log(a); // undefined
    console.log(b); // undefined
    console.log(c); // undefined
    
    // the same applies for `const`

⬆ 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.

    // 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.

    function 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

    // 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

    // 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

    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,
    };

  • 3.8 Prefer the object spread operator over Object.assign to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.

    // very bad
    const original = { a: 1, b: 2 };
    const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
    delete copy.a; // so does this
    
    // bad
    const original = { a: 1, b: 2 };
    const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
    
    // good
    const original = { a: 1, b: 2 };
    const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
    
    const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

⬆ 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.

    // 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);

  • 4.6 Use line breaks after open and before close array brackets if an array has multiple lines

    // bad
    const objectInArray = [{
        id: 1,
    }, {
        id: 2,
    }];
    
    // good
    const objectInArray = [
        {
            id: 1,
        },
        {
            id: 2,
        },
    ];

⬆ back to top

Destructuring

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

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

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

  • 5.2 Use array destructuring.

    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.

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

    // bad
    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
    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

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

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

    Why? Broken strings are painful to work with and make code less searchable.

    // 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

    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();
    }
    
    // bad
    sayHi(name) {
        return `How are you, ${ name }?`;
    }
    
    // good
    sayHi(name) {
        return `How are you, ${name}?`;
    }

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

  • 6.6 Never inject untrusted strings into the DOM unless the value 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) {
        obj.key = 1;
    }
    
    // good
    foo(obj) {
        const key = obj.key != null ? obj.key : 1;
    }

  • 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(name) {
        name = name || 'Tony Stark';
    }
    
    // good
    foo(name) {
        const localName = name || 'Tony Stark';
    }
    
    // good
    foo(name = 'Tony Stark') {
        const localName = name;
    }

  • 7.3 When arguments may be omitted completely, use default parameter syntax.

    // bad
    // This won't work as expected, the default parameter will
    // only be assigned if the value provided is `undefined`
    signup(name = 'Tony Stark') {
        // ...
    }
    signup(null);
    
    // good
    signup(name = 'Tony Stark') {
        // ...
    }
    signup();

  • 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.

    handleThings(opts = {}, name) {
        // ...
    }
    
    // good
    handleThings(name, opts = {}) {
        // ...
    }

  • 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-inner-declarations

    // 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. eslint: no-new-func

    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 Prefer a single return at the end of the function. Avoid adding multiple returns in the middle of a function, since they make the flow harder to debug and encourage inconsistent return types.

    // bad
    login(userId) {
        if (userId != null) {
            return getUser(userId);
        } else {
            return new User();
        }
    };
    
    // good
    login(userId) {
        let user = null;
    
        if (userId != null) {
            user = getUser(userId);
        } else {
            user = new User();
        }
    
        return user;
    };

  • 7.12 An exception to the above for guard clauses: if asserting whether parameters are valid, exit early using return statements at the beginning of the function.

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

  • 7.13 Add parantheses around immediately invoked function expressions. eslint: wrap-iife

    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

    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

    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
    function PeekableQueue(contents) {
        Queue.apply(this, contents);
    }
    PeekableQueue.prototype = new Queue();
    PeekableQueue.prototype.constructor = PeekableQueue;
    
    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 Avoid duplicate class members. eslint: [no-dupe-class-members] (http://eslint.org/docs/rules/no-dupe-class-members)

    Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.

    // bad
    class Foo {
          bar() { return 1; }
          bar() { return 2; }
    }

⬆ 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 In modules with a single export, prefer default export over named export. eslint: import/prefer-default-export

    // bad
    export function foo() {}
    
    // good
    export default function foo() {}

  • 10.4 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.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 instead of loops like for-in or for-of.

    Use map() / every() / filter() / find() / findIndex() / reduce() / some() / ... to iterate over arrays, and Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.

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

  • 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

    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 Use shortcuts for booleans, but explicit comparisons for strings and numbers.

    Why? JavaScript will try to coerce strings and numbers into a boolean value, which could lead to unintended results. Be more descriptive about what you want to compare. For more information see Truth Equality and JavaScript by Angus Croll.

    // bad
    if (isValid === true) {
        // ...
    }
    
    // good
    if (isValid) {
        // ...
    }
    
    // bad
    if (name) {
        // ...
    }
    
    // good
    if (name !== '') {
        // ...
    }
    
    // bad
    if (collection.length) {
        // ...
    }
    
    // good
    if (collection.length > 0) {
        // ...
    }

  • 13.4 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.5 Ternaries should not be nested and should 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. eslint: curly

    // 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

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

⬆ back to top

Comments

  • 15.1 Use /** ... */ for multi-line comments. Include types for all parameters and return values. eslint: valid-jsdoc

    // 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
    getType() {
        console.log('fetching type...');
        // set the default type to 'no type'
        const type = this._type || 'no type';
    
        return type;
    }
    
    // good
    getType() {
        console.log('fetching type...');
    
        // set the default type to 'no type'
        const type = this._type || 'no type';
    
        return type;
    }
    
    // also good
    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

    // bad
    test() {
    ∙∙console.log('test');
    }
    
    // good
    test() {
    ∙∙∙∙console.log('test');
    }

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

    // bad
    test(){
        console.log('test');
    }
    
    // good
    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: keyword-spacing, space-before-function-paren

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

  • 16.4 Set off operators with spaces. eslint: space-infix-ops

    // bad
    const x=y+5;
    
    // good
    const x = y + 5;

  • 16.5 End files with a single newline character. eslint: eol-last

    // 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

    // 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.

    // 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

    // bad
    bar() {
    
        console.log(foo);
    
    }
    
    // also bad
    if (baz) {
    
        console.log(qux);
    } else {
        console.log(foo);
    
    }
    
    // good
    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

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

  • 16.10 Do not add spaces inside brackets. eslint: array-bracket-spacing

    // bad
    const foo = [ 1, 2, 3 ];
    console.log(foo[ 0 ]);
    
    // good
    const foo = [1, 2, 3];
    console.log(foo[0]);

  • 16.11 Add spaces inside curly braces. eslint: object-curly-spacing

    // bad
    const foo = {clark: 'kent'};
    
    // good
    const foo = { clark: 'kent' };

  • 16.12 Functions with multiline signatures, or invocations, should be indented with each item on a line by itself, with a trailing comma on the last item.

    // bad
    function foo(bar,
                 baz,
                 quux) {
      // ...
    }
    
    // good
    function foo(
        bar,
        baz,
        quux,
    ) {
      // ...
    }
    
    // bad
    console.log(foo,
        bar,
        baz);
    
    // good
    console.log(
        foo,
        bar,
        baz,
    );

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

    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 Use trailing commas for multi-line arrays and objects. eslint: comma-style comma-dangle

    Why? This leads to cleaner git diffs.

    // bad
    const heroes = [
        'Batman'
      , 'Superman'
    ];
    
    // bad
    const heroes = [
        'Batman',
        'Superman'
    ];
    
    // good
    const heroes = [
        'Batman',
        'Superman',
    ];
    
    // bad
    const hero = {
        firstName: 'Ada'
      , lastName: 'Lovelace'
    };
    
    // bad
    const hero = {
        firstName: 'Ada',
        lastName: 'Lovelace'
    };
    
    // good
    const hero = {
        firstName: 'Ada',
        lastName: 'Lovelace',
    };

  • 17.2 No trailing commas for single-line arrays and objects. eslint: comma-dangle

    // bad
    const heroes = ['Batman', 'Superman',];
    
    // good
    const heroes = ['Batman', 'Superman'];
    
    // bad
    const hero = { firstName: 'Ada', lastName: 'Lovelace', };
    
    // good
    const hero = { firstName: 'Ada', lastName: 'Lovelace' };

⬆ back to top

Semicolons

  • 18.1 Yup. eslint: semi

    // 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 Plane {
        flew = 0;
        powering = 4;
    
        airborne() {
            // ...
        }
    
        grounded() {
            // ...
        }
    }  
    
    // good
    class Plane {
        altitude = 0;
        engineCount = 4;
    
        takeoff() {
            // ...
        }
    
        land() {
            // ...
        }
    }   

  • 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

    // 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

    // 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.6 Use a leading underscore _ when naming private or protected properties.

    // bad
    this.__firstName__ = 'Panda';
    this.firstName_ = 'Panda';
    
    // good
    this._firstName = 'Panda';

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

    // 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 Constant values should be in all capitals and underscore-separated.

    const MAXIMUM_POWER = 9000;

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

    // bad
    const SELECTOR_ACTIVE = '.isActive';
    const SELECTOR_DISABLED = '.isDisabled';
    const SELECTOR_MODAL_CLOSE = '.js-modal-close';
     
    // good
    const SELECTORS = {
        ACTIVE: '.isActive',
        DISABLED: '.isDisabled',
        MODAL_CLOSE: '.js-modal-close',
     };

  • 19.11 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.1 Prefix jQuery object variables with a $.

    // bad
    const body = $(document.body);
    
    // good
    const $body = $(document.body);

  • 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. Better yet, use the await syntax.

    // 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!');
        });
    
    // best
    async function mySequence() {
        await waitFor(1000);
        await waitFor(2000);
        await waitFor(3000);
        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-2017 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

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%