JavaScript Naming Conventions


In this post, I would like to discuss JavaScript naming conventions with an example.

JavaScript Naming Conventions

1. Avoid single letter names. Be descriptive with your naming.
// bad
function d() {
  // ...stuff...
}

// good
function display() {
  // ..stuff..
}
2. Use camelCase when naming objects, functions, and instances
// bad
var EMployee= {};
var this_is_my_object = {};
function c() {}
var u = new user({
  name: 'Bob Parr'
});

// good
var thisIsMyObject = {};
function thisIsMyFunction() {}
var user = new User({
  name: 'Bob Parr'
});
3. 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'
});
4. Use a leading underscore _ when naming private properties
// bad
this.__firstName__ = 'ramesh';
this.firstName_ = 'ramesh';

// good
this._firstName = 'ramesh';
5. When saving a reference to this use _this.
// bad
function() {
  var self = this;
  return function() {
    console.log(self);
  };
}

// bad
function() {
  var that = this;
  return function() {
    console.log(that);
  };
}

// good
function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
}
6. 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);
};
7. 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';
8. Use camelCase when you export-default a function. Your filename should be identical to your function's name.
function makeStyleGuide() {
}

export default makeStyleGuide;

Reference


Comments