Naming Conventions for NodeJS

In the dynamic world of Node.js development, code readability and maintainability are crucial. One of the simplest yet most effective ways to achieve this is through consistent naming conventions. Naming conventions not only help in understanding the code at a glance but also ensure that your codebase is scalable and easy to manage as your project grows. In this blog post, we’ll explore some best practices for naming conventions in Node.js that can elevate your coding standards.

Prefer Dashes over other definitions for filenames

// good
// fetch-sync.ts
export function fetchSync(endpoint: string){}
...
// bad
// fetchSync.ts
export function fetchSync(endpoint: string){}

...
// good
// fetch-async.ts
export const fetchAsync = async (endpoint: string) => {}
...
// bad
// fetchAsync.ts
export const fetchAsync = async (endpoint: string) => {}
// good
// foo-bar.ts
export class FooBar {
  ...
}
...
// bad
// fooBar.ts or FooBar.ts
export class FooBar {
  ...
}
// good
// console-message.ts
export const ConsoleMessage = {
  ...
}
...
// bad
// consoleMessage.ts or ConsoleMessage.ts
export const ConsoleMessage = {
  ...
}
// good
// http-status.ts
export enum HttpStatus {
  Ok = 200,
  BadRequest = 400
}
...
// bad
// httpStatus.ts or HttpStatus.ts
export enum HttpStatus {
  Ok = 200,
  BadRequest = 400
}

If file belongs a to spec (unit test) denote that using .spec.ts

// good
// fetsch-async.spec.ts
describe('fetchAsync', () => {
  ...
})
...
// bad
// fetschAsync.spec.ts
describe('fetchAsync', () => {
  ...
})

Suggestion for: type vs interface

Suggestion for Types

  • Use PascalCase for name.
  • Use camelCase for members.
// good
type Foo = {
  foo: string;
  fooBar: number
};
...
// bad
type foo = {
  foo: string;
  fooBar: number
}

// bad
type Foo = {
  Foo: string;
  FooBar: number
}

Suggestion for Interfaces

  • Use PascalCase for name.
  • Use camelCase for members.
  • Don’t prefix with I
// good
interface Foo {
  foo: string;
  fooBar: number
};

...
// bad
interface FooI {
  foo: string;
  fooBar: number
};

// bad
interface IFoo {
  foo: string;
  fooBar: number
};

Suggestion for Classes

  • Use PascalCase for class names.
  • Use camelCase of class members and methods
// good
class Bar {
  private foo: string;
  fooBar(){
    return 'foo-bar';
  }
}
...
// bad
class bar {
  private foo: string;
  fooBar(){
    return 'foo-bar';
  }
}

Suggestion for Namespaces

Class names are PascalCase => Namespace names are PascalCase

  • Use PascalCase for names
// good
namespace Bar {
}
...
// bad
namespace bar {
}

Suggestion for Enums

  • Use PascalCase for enum names
  • Use PascalCase for enum member
// good
enum Foo {
  Foo,
  Bar
}
...
// bad
enum foo {
  Foo,
  Bar
}
...
// bad
enum Foo {
  foo,
  bar
}

Keep pushing forward and savor every step of your coding journey.