JavaScript Naming Conventions

Brijesh Dobariya - Feb 29 - - Dev Community

One of the most widely used languages for building websites, JavaScript places a premium on well-structured, consistent code. An essential part of writing readable and manageable JavaScript code involves sticking to naming rules.

The importance of naming conventions in JavaScript

When creating and maintaining code, JavaScript naming standards are essential. They help with project-wide readability, maintainability, and teamwork. Some important reasons why JavaScript naming conventions should be followed are as follows:

  • Code Readability
  • Code Maintainability
  • Reduced Cognitive Load
  • Consistency Across Projects
  • Collaboration and Teamwork
  • Debugging and Troubleshooting
  • Scalability
  • Code Reviews
  • Preventing Naming Conflicts
  • Cross-Language Consistency

Proper naming standards improve the clarity of your code and its general quality. This blog post will cover 12 JavaScript naming conventions that every developer should know to produce more robust and maintainable code.

1. VARIABLES

Camel case is the proper way to declare variables in JavaScript. This indicates that the variable name should begin with a lowercase letter and continue with an uppercase letter.

Data is stored in variables in JavaScript. It is critical to give variables descriptive names that appropriately reflect their purpose. You could, for example, use userName or userAge as variable names instead of x.

let userName = "JohnDoe";
let userAge = 25;
let isLoggedIn = true;

console.log(userName); // Output: JohnDoe
console.log(userAge); // Output: 25
console.log(isLoggedIn); // Output: true

Enter fullscreen mode Exit fullscreen mode

2. BOOLEANS

In JavaScript, true or false values are represented by Booleans. Use the prefix “is” or “has” before the name of a boolean variable to make it easier to understand the code. The variable’s nature can be more precisely communicated using this convention. Commonly, the first word is written in lowercase and all the words that follow it are capitalized referred to as camel case.

let isReady = true;
let hasPermission = false;

console.log(isReady); // Output: true
console.log(hasPermission); // Output: false

Enter fullscreen mode Exit fullscreen mode

3. FUNCTION

Make an effort to be consistent and clear when naming functions. Pick a verb-noun pair that defines the function’s purpose clearly but concisely. This is also a camel case.

function calculateTotalPrice(itemPrice, quantity) {
    return itemPrice * quantity;
}

console.log(calculateTotalPrice(10, 5)); // Output: 50

Enter fullscreen mode Exit fullscreen mode

4. CLASS

In JavaScript, classes use the Pascal case convention for their constructors. The class name is capitalized to make it stand out from other variables and functions.

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }

    startEngine() {
        console.log(`${this.make} ${this.model}'s engine started.`);
    }
}

const myCar = new Car("Toyota", "Camry");
myCar.startEngine();

// Output: Toyota Camry's engine started.

Enter fullscreen mode Exit fullscreen mode

5. METHODS

The naming standards for regular functions and methods, which are functions that are properties of objects or classes, should be consistent. Name your methods using camel case.

class Dog {
    bark() {
        console.log("Woof! Woof!");
    }
}

const myDog = new Dog();
myDog.bark();

// Output: Woof! Woof!

Enter fullscreen mode Exit fullscreen mode

6. GLOBAL VARIABLES

The global variables can cause naming and scope conflicts; global variables should be avoided at all costs. If you insist on using one, though, be careful to give it a meaningful name. To reduce the likelihood of problems, try prefixing your variables with “global” or utilizing a named scope.

At the very beginning of a project or file, you can declare a global variable in JavaScript.
If a worldwide JavaScript variable is mutable, it is typed in camelCase.
If a global JavaScript variable is immutable, it is written in UPPERCASE.

let globalCounter = 0;

function incrementCounter() {
    globalCounter++;
}

incrementCounter();
console.log(globalCounter);

// Output: 1

Enter fullscreen mode Exit fullscreen mode

7. COMPONENT

A large part of front-end development is devoted to components. Components should be named in a way that conveys their function. For uniformity, a camel case is ideal.

class HeaderComponent {
    constructor() {
        // Component initialization logic
    }

    render() {
        // Render component logic
    }
}

const headerComponent = new HeaderComponent();
headerComponent.render();

// Output: Render component logic (example)

Enter fullscreen mode Exit fullscreen mode

8. PRIVATE

Developers frequently rely on conventions to indicate privacy, as JavaScript does not have built-in support for private members. The purpose of appending an underscore to an identifier is to make it secret. It also uses camel case.

class Example {
    _privateVariable = 42;

    getPrivateVariable() {
        return this._privateVariable;
    }
}

const example = new Example();
console.log(example.getPrivateVariable()); // Output: 42

Enter fullscreen mode Exit fullscreen mode

9. FILES

An essential part of managing a JavaScript project effectively is keeping files organized. Use lowercase letters and hyphens to divide words within file names for simplified and consistent naming practices.

Due to JavaScript’s case sensitivity, which means it handles lowercase and uppercase letters differently, it is recommended to utilize lowercase letters. When referring to files in the code, it’s best to use lowercase letters to maintain consistency and prevent misunderstanding.

Since spaces are not permitted in file names, hyphens are utilized to separate words. Hyphens are typically favored for their readability; however, underscores or camelCase are also acceptable alternatives.

// Filename: my_module.js

10. CONSTANT

Standard practice dictates that constants, which stand for immutable values, must be written in capital with underscores between each word.

const MAX_COUNT = 100;
const API_KEY = "your-api-key";

console.log(MAX_COUNT); // Output: 100
console.log(API_KEY); // Output: your-api-key

Enter fullscreen mode Exit fullscreen mode

11. UNDERSCORE

Underscores are used differently in JavaScript. Consistency is vital inside your codebase, even though it’s a practice to prefix with an underscore to denote anonymity.

let _privateVariable = 42;

function _privateFunction() {
    // Private function logic
}

console.log(_privateVariable); // Output: 42
_privateFunction(); // Output: No output (function call, but not logged)

Enter fullscreen mode Exit fullscreen mode

12. DASH

For more excellent readability, dashes are usually included in filenames. If a CSS class name contains more than one word, dashes are the correct way to do it.

/* In a stylesheet (no JavaScript output) */

.my-style {
    color: blue;
    font-size: 16px;
}

Enter fullscreen mode Exit fullscreen mode

Follow us on Github, Twitter, Linkedin, Facebook, and Dribbble.

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player