Home  >  Article  >  Web Front-end  >  Naming rules for variables in javascript

Naming rules for variables in javascript

下次还敢
下次还敢Original
2024-05-08 22:48:19374browse

JavaScript variable naming rules stipulate: avoid using reserved words. Use camel nomenclature, starting with a lowercase letter and capitalizing the first letter of each new word. Use descriptive names that clearly state what the variable does. Add a prefix to indicate the variable type or purpose. Avoid using underscores. case sensitive. Variable names start with a letter and avoid numbers.

Naming rules for variables in javascript

JavaScript variable naming rules

The naming rules of variables in JavaScript are crucial and help to enhance the code readability, maintainability and debugging capabilities. Here’s how to properly name variables in JavaScript:

Rule 1: Avoid using reserved words

Reserved words are special keywords that JavaScript reserves for specific purposes and cannot Used as variable name. For example:

<code>let if = 10; // 错误:if是保留字</code>

Rule 2: Use camel nomenclature

Camel nomenclature starts with a lowercase letter and the first letter of each new word is capitalized. For example:

<code>let myVariable = "Hello";</code>

Rule 3: Use descriptive names

Variable names should clearly describe what the variable does. Avoid using vague or generic names such as:

<code>let a = 10; // 不好
let studentName = "John"; // 好</code>

Rule 4: Use appropriate prefixes

Prefixing a variable helps indicate its type or purpose. For example:

  • i or j: Loop variable
  • str: String variable
  • num: Numeric variable
  • obj: Object variable

Rule 5: Avoid using underscores

Underscores are generally not used as part of variable names in JavaScript. Instead, camel nomenclature should be used.

Rule 6: Case Sensitive

JavaScript is case sensitive, so variable names should be case sensitive. For example:

<code>let firstName = "John";
let firstname = "Jane"; // 不同变量</code>

Rule 7: Avoid numbers starting with variable names

Variable names should start with letters and avoid numbers. For example:

<code>let 1stVariable = 10; // 错误
let firstVariable = 10; // 正确</code>

Following these naming conventions will make your JavaScript code easier to read, maintain, and debug.

The above is the detailed content of Naming rules for variables in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn