Naming conventions for modern JavaScript
If you're like me, you've struggled to come up with a reasonable scheme for naming things in JavaScript. I'd like to share the conventions I use, with the hope that you can put them to use in your project and never think about it again.
In my mind, there are three main types of JavaScript files:
- Collections of functions
- Single functions
- Classes
Collections of functions
Let's say you have a couple utility functions called add
and subtract
,
each exported from a single file:
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
When I have a group of functions like this, I name the file using drunkenCamelCase
,
(lowercase first letter) with a name that suggests the library's contents. This module
I'd probably call math.js
.
When I go to use one of the functions from another file, now I can refer to it like so:
import { subtract } from 'math';
console.log(subtract(5, 1));
Single functions
What if you have a single helper function you want to use from a few places in your codebase that you'd like to give its own file?
For instance, let's say you have a function that generates a fully-qualified URL from a URL path:
export default function(path) {
return "http://www.guilded.co" + path;
}
In this case, I'd name the file using drunken camel case, but would name the file explicitly after the exported function. That way, when I go to import it from another file, I can refer to it thusly:
import urlFor from 'urlFor';
console.log(urlFor('/about.html'));
Classes
Now that ES6 has support for classes built into the language, there's a good chance you'll use them to represent the stateful objects in your codebase.
I like to make it clear that classes are distinct from functions, so I name them
using CamelCase
(capital first letter) notation:
class MyClass {
// ...
}
When producing a new file for a class, export the class directly, omitting its name:
export default class {
// ...
}
File names for classes should be CamelCased
as well. So our MyClass
class
would be in MyClass.js
.
If you use React, you probably know you're required to name React components in
the same CamelCased
format. If you use ES6 classes to construct your React
components, this convention will come in handy.