Naming Conventions

Naming Conventions

  • Avoid single letter names. Be descriptive with your naming.

    // bad
    function q() {
      // ...stuff...
    }
    
    // good
    function query() {
      // ..stuff..
    }
    
  • Use camelCase when naming objects, functions, and instances.

    // bad
    var OBJEcttsssss = {};
    var this_is_my_object = {};
    var o = {};
    function c() {}
    
    // good
    var thisIsMyObject = {};
    function thisIsMyFunction() {}
    
  • Use PascalCase when naming constructors or classes.

    // bad
    function user(options) {
      this.name = options.name;
    }
    
    var bad = new user({
      name: 'nope'
    });
    
    // good
    function User(options) {
      this.name = options.name;
    }
    
    var good = new User({
      name: 'yup'
    });
    
  • Do not use trailing or leading underscores.

    Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.

    // bad
    this.__firstName__ = 'Panda';
    this.firstName_ = 'Panda';
    this._firstName = 'Panda';
    
    // good
    this.firstName = 'Panda';
    
  • Don’t save references to this. Use Function#bind.

    // bad
    function () {
      var self = this;
      return function () {
        console.log(self);
      };
    }
    
    // bad
    function () {
      var that = this;
      return function () {
        console.log(that);
      };
    }
    
    // bad
    function () {
      var _this = this;
      return function () {
        console.log(_this);
      };
    }
    
    // good
    function () {
      return function () {
        console.log(this);
      }.bind(this);
    }
    
  • Name your functions. This is helpful for stack traces.

    // bad
    var log = function (msg) {
      console.log(msg);
    };
    
    // good
    var log = function log(msg) {
      console.log(msg);
    };
    
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

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

    // file contents
    class CheckBox {
      // ...
    }
    module.exports = CheckBox;
    
    // in some other file
    // bad
    var CheckBox = require('./checkBox');
    
    // bad
    var CheckBox = require('./check_box');
    
    // good
    var CheckBox = require('./CheckBox');
    

⬆ Back to Table of Contents