[go: up one dir, main page]

DEV Community

Gulshan
Gulshan

Posted on

Naming Conventions In Javascript

Introduction

Labels and names are everywhere. It is one of the ways for us to recognize something. And if the name is not enough, we would describe the thing and make it understandable for others. But imagine you have only a word to use for the identity of a thing then it has to be descriptive or at least one should know what to expect.

In this article, we discuss why we need naming conventions, what are some of the common patterns to use, and how it helps in code quality.

Naming Conventions

We can divide this topic into two parts for a better understanding

  • Style Guide and Standards

  • Finding a good name

Style Guide and Standards

Integrating code formatting tools and linters is the workspace a common practice for developers. We even have built-in code formatters in VSCode. It takes care of formatting our code to look readable and standard, detects errors, assures following style guide, auto-completes and more. However, it can not assure the actual quality of the code, and whether or not it will work as you intended.

Similarly, for naming, we do have the standards, do's and dont's and the best practices that can be followed and it makes it a lot better to just by following these standards.

Robin Wieruch has a great post about Javascript naming conventions which is really useful as a cheat sheet or to provide a reference to others as well in code reviews or in general.

Google javascript style guide has a whole topic on naming, which will cover almost everything you need to know as far as the standards go. This is a more lengthy resource than the previous one but it is in a fairly compact and precise manner and is easy to understand.

Following these resources will make a real difference for the code quality. It will make the code more readable, consistent across the codebase, more predictable, cleaner and easy to review.

Finding A Good Name

Even when following the standards and style guide for naming, it is still possible to write some pretty bad names.

We are free to name our variables and functions how we'd like to, there is really no limitations or hard standards present. And as long as you work on a solo project or a small codebase, it would be perfectly fine to have no stress on this topic.

But better naming is certainly important and could affect the developer experience when it comes to maintaining large applications, working in a team, or contributing to open-source.

Here are some of the best practices that I have identified

No single-letter name

const onChange = (e) => console.log(e)
// e stands for event, element or error?
Enter fullscreen mode Exit fullscreen mode

No single word name

Using a single word leaves a lot of meaning to guesswork and assumptions.

// avoid
let template;

// instead use
let templateID
let themeTemplate
let templateTitle
let templateSVG
Enter fullscreen mode Exit fullscreen mode

Count

Use singular or plural names based on the count of it's content.

// avoid
let selectedBookID = [3112, 332]

// instead
let selectedBookIDs
Enter fullscreen mode Exit fullscreen mode

Re-evaluate the name after writing the code

After writing the code, we can often find better clarity and be able to describe it better than we could before it was written down. That is a good time to revisit the name if necessary.

Avoid the use of "data" in the name

Calling some data, "data", is like calling a person "person" instead of their name. Still, the word data is used a lot in naming. It is okay to use when the "data" is really complex to describe, but trying to avoid this word could lead to a much more descriptive name.

Specify the type of content

Specifying the type of content such as list, object, number etc. helps us to know what to expect and how we can use the variable or constant.

// avoid
const countries

// instead
const countryList
const countryDetails
Enter fullscreen mode Exit fullscreen mode

Group relevant data

// avoid
const instagramLink
const twitterLink
const youtubeLink

// instead
const socialLinks = {
    instagram: '...',
    twitter: '..',
    youtube: '...'
}
Enter fullscreen mode Exit fullscreen mode

Avoid redundant information

// avoid
const imageList = {
    userImage: '..',
    adminImage: '...'
    ...
}
// instead
const brandImageList = {
    user: '..',
    admin: '...'
    ...
}
Enter fullscreen mode Exit fullscreen mode

Add context

// avoid
const userActions

// instead
const userReduxActions
Enter fullscreen mode Exit fullscreen mode

Get more specific

// this is okay
const getUser = ()=> ...

// this is better
const getUserByID = ()=> ...
const getUserByEmail = ()=> ...
Enter fullscreen mode Exit fullscreen mode

Easy to import

Make sure the name makes it easier to auto-import the variable. Using some consistent patterns for naming can also make it more predictable and convenient to find or auto-import.

// examples
type BookDetailsType

const BOOK_CATEGORIES
Enter fullscreen mode Exit fullscreen mode

Avoid duplicate naming

Avoid duplicate naming, even if they exist in completely different modules and are properly sorted by directories.

// example
let CATEGORIES // in books module
let CATEGORIES // in music module
let CATEGORIES // in videos module
// and so on.. Even though these variables exist in isolated modules but all of these will be part of the global search result. It prevents us from being more specific with the operations we try to perform (find, debug, replace etc.)

// instead we can
let BOOK_CATEGORIES
let MUSIC_CATEGORIES
let VIDEO_CATEGORIES
Enter fullscreen mode Exit fullscreen mode

Describe functions with verbs

// examples
const getBookDetails
const formatDateByRegion
const setDefaultUserState
const generateRandomID
Enter fullscreen mode Exit fullscreen mode

General vs specific names

Only use generalised names when a function or variable is usable generally and not only in a specific use case. If it is not usable across multiple modules without any modification, then opt for a more specific name. This lets others know when they should try using your function etc.

Meaning > Length

Hard to understand name can cost us more than a longer name. However, it is important to keep the name short.

// example
const minToHrs // not searchable, doesn't suggest it is a function

// instead
const getHoursByMinutes // clearer, easy to remember/pronounce, predictable parameter and result
Enter fullscreen mode Exit fullscreen mode

Describing the data type of the value

// this is okay
const selectedBook

// this is better
const selectedBookTitle; // seems like a string.
const selectedBookID; // should be a number!
Enter fullscreen mode Exit fullscreen mode

Identifying patterns or rules for naming different types of constants/variables

Finally, I would like to encourage you to identify more of such patterns or rules to follow, that could be specific to your team and codebase.

E.g. Adding Type at the end of all typescript types. It will prevent clashing with the same name that might be used for a variable or constant and it makes code review easier.

Conclusion

We discussed the difference between naming conventions and finding a good name, and what are some of the naming conventions and standards to follow

We also discussed some of the patterns with examples, to achieve good naming.

Take a look at the links below to learn more about the topic.

Thanks for reading!

Links

https://www.robinwieruch.de/javascript-naming-conventions/

https://github.com/ryanmcdermott/clean-code-javascript#variables

https://google.github.io/styleguide/jsguide.html#naming

Top comments (1)

Collapse
 
axorax profile image
Axorax

nice!