Skip to content

Naming conventions

Darya Solomakha edited this page Nov 3, 2020 · 1 revision

JAVASCRIPT NAMING CONVENTIONS

VARIABLES

JavaScript variables are case sensitive. Therefore, JavaScript variables with lowercase and uppercase characters are different:

var name = 'Robin Wieruch';
 
var Name = 'Dennis Wieruch';
 
var NAME = 'Thomas Wieruch';
 
console.log(name);
// "Robin Wieruch"
 
console.log(Name);
// "Dennis Wieruch"
 
console.log(NAME);
// "Thomas Wieruch" 

A JavaScript variable should be self-descriptive. It shouldn't be necessary to add a comment for additional documentation to the variable:

// bad
var val = 'Robin';
// good
var firstName = 'Robin';

Most often you will find JavaScript variables declared with a camelCase variable name with a leading lowercase character:

// bad
var firstname = 'Robin';`

// bad
var first_name = 'Robin';

// good
var firstName = 'Robin';

BOOLEAN

A prefix like is, are, or has helps every JavaScript developer to distinguish a boolean from another variable by just looking at it:

// good

var isVisible = true;

var areEqual = false;

var hasEncryption = true;

In contrast to strings and integers, you can see it as another soft rule for a JavaScript boolean naming convention besides being written in camel case.

FUNCTION

JavaScript functions are written in camel case too. In addition, it's a best practice to actually tell what the function is doing by giving the function name a verb as prefix. This verb as prefix can be anything (e.g. get, fetch, push, apply, calculate, compute, post). It's yet another soft rule to consider for having more self-descriptive JavaScript variables.

// bad
function name(firstName, lastName) {
  return `${firstName} ${lastName}`;
}
 
// good
function getName(firstName, lastName) {
  return `${firstName} ${lastName}`;
}

CLASS

A JavaScript class is declared with a PascalCase in contrast to other JavaScript data structures:

class SoftwareDeveloper {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}
 
var me = new SoftwareDeveloper('Robin', 'Wieruch');

COMPONENT

Since a component is kinda instantiated -- but appended to the DOM instead -- like a JavaScript class, they are widely declared with Pascal Case too. When a component gets used, it distinguishes itself from native HTML and web components, because its first letter is always written in uppercase.

// bad
function userProfile(user) {
  return (
    <div>
      <span>First Name: {user.firstName}</span>
      <span>Last Name: {user.lastName}</span>
    </div>
  );
}
 
// good
function UserProfile(user) {
  return (
    <div>
      <span>First Name: {user.firstName}</span>
      <span>Last Name: {user.lastName}</span>
    </div>
  );
}
<div>
  <UserProfile
    user={{ firstName: 'Robin', lastName: 'Wieruch' }}
  />
</div>

METHODS

Identical to JavaScript functions, a method on a JavaScript class is declared with camelCase. Here the same rules as for JavaScript functions apply -- e.g. adding a verb as a prefix --, for making the method name more self-descriptive.

class SoftwareDeveloper {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
 
  getName() {
    return `${this.firstName} ${this.lastName}`;
  }
}
 
var me = new SoftwareDeveloper('Robin', 'Wieruch');
 
console.log(me.getName());
// "Robin Wieruch"

PRIVATE

Rarely you will find an underscore (_) in front of a variable/function/method in JavaScript. If you see one, it is intended to be private. Even though it cannot be really enforced by JavaScript, declaring something as private tells us about how it should be used or how it should not be used.

For instance, a private method in a class should only be used internally by the class, but should be avoided to be used on the instance of the class.

A private variable/function can occur in a JavaScript file as well. This could mean that the variable/function shouldn't be used outside of this file but only internally to compute further business logic for other functions within the same file.

class SoftwareDeveloper {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.name = _getName(firstName, lastName);
  }
 
  _getName(firstName, lastName) {
    return `${firstName} ${lastName}`;
  }
}
 
var me = new SoftwareDeveloper('Robin', 'Wieruch');
 
// good
var name = me.name;
console.log(name);
// "Robin Wieruch"
 
// bad
name = me._getName(me.firstName, me.lastName);
console.log(name);
// "Robin Wieruch"

CONSTANT

Last but not least, there are constants -- intended to be non-changing variables -- in JavaScript which are written in capital letters (UPPERCASE). If a variable has more than one word in its variable declaration name, it makes use of an underscore (_):

var SECONDS = 60;
var MINUTES = 60;
var HOURS = 24;
 
var DAY = SECONDS * MINUTES * HOURS;

var DAYS_UNTIL_TOMORROW = 1;

GLOBAL VARIABLE

  • A global JavaScript variable is declared at the top of a project/file.
  • A global JavaScript variable is written in camelCase if it is mutable.
  • A global JavaScript variable is written in UPPERCASE if it is immutable.

UNDERSCORE & DASH

So what about the underscore and dash in JavaScript variable namings? Since camelCase and PascalCase are primarily considered in JS, you have seen that the underscore is only rarely used for private variables or constants. Occasionally you will find underscores when getting information from third-parties like databases or APIs. Another scenario where you might see an underscore are unused function parameters, but don't worry about these yet if you haven't seen them out there ;-)

A dash in a JavaScript variable isn't common sense as well. It just makes things more difficult; like using them in an object.

FILES

There are two strategies of naming files in JavaScript: PascalCase and kebab-case. In JavaScript frontend applications, you will often see PascalCase for naming components (e.g. React components).

- components/
--- user/
----- UserProfile.js
----- UserList.js
----- UserItem.js
--- ui/
----- Dialog.js
----- Dropdown.js
----- Table.js

In contrast, in JavaScript backend application, kebab-case is the common sense:

- routing/
--- user-route.js
--- messages-route.js

CSS NAMING CONVENTIONS

A BEM class name includes up to three parts.

  1. Block: The outermost parent element of the component is defined as the block.
  2. Element: Inside of the component may be one or more children called elements.
  3. Modifier: Either a block or element may have a variation signified by a modifier.

If all three are used in a name it would look something like this:

[block]__[element]--[modifier]

Component With No Elements or Modifiers

Simple components may only employ a single element and thus a single class which would be the block.

<button class=”btn”></button>

<style>
  .btn {}
</style>  

Component With A Modifier

A component may have a variation. The variation should be implemented with a modifier class.

<!-- DO THIS -->
<button class="btn btn--secondary"></button>

<style>
  .btn {
    display: inline-block;
    color: blue;
  }
  .btn--secondary {
    color: green;
  }  
</style> 

Don’t use the modifier class by itself. The modifier class is intended to augment, not replace, the base class.

<!-- DON'T DO THIS -->
<button class="btn--secondary"></button>

<style>
  .btn--secondary {
    display: inline-block;
    color: green;
  }  
</style> 

Component With Elements

More complex components will have child elements. Each child element that needs styled should include a named class.

One of the purposes behind BEM is to keep specificity low and consistent. Don’t omit class names from the child elements in your HTML. That will force you to use a selector with increased specificity to style those bare elements inside the component (see img and figcaption elements below). Leaving those classes off may be more succinct, but you will increase risks of cascade issues in the future. One goal of BEM is for most selectors to use just a single class name.

<!-- DO THIS -->
<figure class="photo">
  <img class="photo__img" src="me.jpg">
  <figcaption class="photo__caption">Look at me!</figcaption>
</figure>

<style>
  .photo { } /* Specificity of 10 */
  .photo__img { } /* Specificity of 10 */
  .photo__caption { } /* Specificity of 10 */
</style>

<!-- DON'T DO THIS -->
<figure class="photo">
  <img src="me.jpg">
  <figcaption>Look at me!</figcaption>
</figure>

<style>
  .photo { } /* Specificity of 10 */
  .photo img { } /* Specificity of 11 */
  .photo figcaption { } /* Specificity of 11 */
</style>
<!-- DON'T DO THIS -->
<figure class="photo">
  <img class="photo__img" src="me.jpg">
  <figcaption class="photo__caption">
    <blockquote class="photo__caption__quote"> <!-- never include more than one child element in a class name -->
      Look at me!
    </blockquote>
  </figcaption>
</figure>

Element With Modifier

In some cases, you may want to vary a single element in a component. In those cases add a modifier to the element instead of the component. I’ve found that modifying elements is much less common and less useful than modifying entire components.

<figure class="photo">
  <img class="photo__img photo__img--framed" src="me.jpg">
  <figcaption class="photo__caption photo__caption--large">Look at me!</figcaption>
</figure>

<style>
  .photo__img--framed {
    /* incremental style changes */
  }
  .photo__caption--large {
    /* incremental style changes */
  }
</style>

Style Elements Based on the Component Modifier

If you find yourself consistently modifying elements of the same component together in the same way, then consider adding the modifier to the base of the component and adjusting styles for each child element based on that one modifier. This will increase specificity, but it makes modifying your component much simpler.

<!-- DO THIS -->
<figure class="photo photo--highlighted">
  <img class="photo__img" src="me.jpg">
  <figcaption class="photo__caption">Look at me!</figcaption>
</figure>

<style>
  .photo--highlighted .photo__img { }
  .photo--highlighted .photo__caption { }
</style>

<!-- DON'T DO THIS -->
<figure class="photo">
  <img class="photo__img photo__img--highlighted" src="me.jpg">
  <figcaption class="photo__caption photo__caption--highlighted">Look at me!</figcaption>
</figure>

<style>
  .photo__img--highlighted { }
  .photo__caption--highlighted { }
</style>

Multi-word Names

BEM names intentionally use double underscores and double hyphens instead of single to separate Block-Element-Modifier. The reason is so that single hyphens can be used as word separators. Class names should be very readable, so abbreviation isn’t always desirable unless the abbreviations are universally recognizable.

<!-- DO THIS -->
<div class="some-thesis some-thesis--fast-read">
  <div class="some-thesis__some-element"></div>
</div>

<style>
  .some-thesis { }
  .some-thesis--fast-read { }
  .some-thesis__some-element { }
</style>

<!-- DON'T DO THIS -->
// These class names are harder to read
<div class="somethesis somethesis--fastread">
  <div class="somethesis__someelement"></div>
</div>

<style>
  .somethesis { }
  .somethesis--fastread { }
  .somethesis__someelement { }
</style>

Useful links:

  1. JavaScript Naming Conventions
  2. BEM by Example
  3. Naming
  4. How to name css classes