Identifiers are names that you assign to variables, functions, objects, etc., in JavaScript. Following proper naming conventions is important for code readability, maintainability, and consistency. Here are the key guidelines and best practices for naming identifiers in JavaScript:

  1. General Rules

    • Start with a Letter, Underscore (_), or Dollar Sign ($): Identifiers cannot start with numbers.
      let myVariable; // Valid
    let _myVariable; // Valid
    let $myVariable; // Valid
    let 1myVariable; // Invalid
      
    • Case Sensitivity: Identifiers are case-sensitive.
      let myVariable;
    let MyVariable; // Different from myVariable
      
    • Unicode Letters: You can use Unicode letters as part of identifiers.
      let café = "coffee"; // Valid
      
  2. Variables and Functions

    • CamelCase: Use camelCase for variable and function names. The first letter is lowercase, and subsequent words start with an uppercase letter.
      let myVariable = 10;
    function calculateSum(a, b) {
        return a + b;
    }
      
    • Descriptive Names: Choose meaningful and descriptive names that make the code self-explanatory.
      let totalAmount = 100; // Clear and descriptive
    let ta = 100; // Not clear
      
  3. Constants

    • Uppercase with Underscores: Use uppercase letters with underscores for constants.
      const MAX_USERS = 50;
    const API_KEY = '123456';
      
  4. Classes

    • PascalCase: Use PascalCase for class names, where each word starts with an uppercase letter.
      class UserAccount {
        constructor(name, balance) {
            this.name = name;
            this.balance = balance;
        }
    }
      
  5. Private Properties and Methods (Convention)

    • Leading Underscore: Use a leading underscore to indicate private properties and methods (not enforced by JavaScript, but a common convention).
      class User {
        constructor(name) {
            this._name = name; // Private property
        }
    
        _displayUser() { // Private method
            console.log(this._name);
        }
    }
      
  6. Avoid Reserved Words

    • JavaScript Keywords: Do not use JavaScript reserved keywords as identifiers.
      let break; // Invalid
    let for; // Invalid
      

Examples

Here are some examples following these conventions:

  // Variables
let userName = "John";
let userAge = 25;
const MAX_ATTEMPTS = 3;

// Functions
function getUserInfo(userId) {
    // Function logic
    return userId;
}

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

    displayInfo() {
        console.log(`${this.make} ${this.model}`);
    }
}

// Private properties and methods (by convention)
class Account {
    constructor(balance) {
        this._balance = balance;
    }

    _calculateInterest() {
        // Private method logic
    }

    getBalance() {
        return this._balance;
    }
}