JavaScript Style Guide


All JavaScript projects follow the same style guide.


JavaScript Style Guide

A style guide usually includes the following aspects:

  • Naming rules for variables and functions
  • Rules for using spaces, indentation, and comments.
  • Other common conventions...

Standardized code is easier to read and maintain.

Code conventions are generally defined before development and can be negotiated and set with your team members.


Variable Names

Variable names are recommended to use camelCase (camelCase):

firstName = "John";
lastName = "Doe";

price = 19.90;
tax = 0.20;

fullPrice = price + (price * tax);

Spaces and Operators

Usually, spaces should be added before and after operators ( = + - * / ):

Example:

var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];

Code Indentation

Usually use 4 spaces to indent code blocks:

Function:

function toCelsius(fahrenheit) {
    return (5 / 9) * (fahrenheit - 32);
}
Note It is not recommended to use the TAB key for indentation, because different editors interpret the TAB key differently.

Statement Rules

General rules for simple statements:

  • A statement usually ends with a semicolon.

Example:

var values = ["Volvo", "Saab", "Fiat"];

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};

General rules for complex statements:

  • Put the opening brace at the end of the first line.
  • Add a space before the opening brace.
  • Put the closing brace on its own line.
  • End a complex statement with a semicolon.

Function:

function toCelsius(fahrenheit) {
    return (5 / 9) * (fahrenheit - 32);
}

Loops:

for (i = 0; i < 5; i++) {
    x += i;
}

Conditional Statements:

if (time < 20) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}

Object Rules

Rules for object definitions:

  • Put the opening brace on the same line as the class name.
  • There is a space between the colon and the property value.
  • Strings use double quotes; numbers do not need them.
  • Do not add a comma after the last property value.
  • Put the closing brace on its own line and end it with a semicolon.

Example:

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};

Short object code can be written directly on one line:

Example:

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Each line of code less than 80 characters

For easy reading, it is recommended that each line have fewer than 80 characters.

If a JavaScript statement exceeds 80 characters, it is recommended to break the line after an operator or comma.

Example:

document.getElementById("demo").innerHTML =
    "Hello Example.";

Try It Yourself »

Naming Rules

Generally, many programming languages have similar naming rules, for example:

  • Variables and functions are identified using lower camel case, that is, except for the first word, the first letter of other words is capitalized (lowerCamelCase)
  • Global variables are uppercase (UPPERCASE )
  • Constants (such as PI) are uppercase (UPPERCASE )

Do you use these rules for variable naming:hyp-hens, camelCase, orunder_scores ?

The hyphen (-) character in HTML and CSS:

HTML5 attributes can use data- as a prefix (e.g., data-quantity, data-price).

CSS uses - to connect property names (font-size).

Note - is usually considered subtraction in JavaScript, so it is not allowed.

Underscore:

Many programmers prefer to use underscores (e.g., date_of_birth), especially in SQL databases.

The PHP language usually uses underscores.

PascalCase:

PascalCase is more common in C language.

Camel case:

Camel case is generally recommended in JavaScript; jQuery and other JavaScript libraries use camel case.

Note Variable names should not start with $, as it will conflict with many JavaScript libraries.

Loading External JavaScript Files in HTML

Use a concise format to load JavaScript files (the type attribute is not required):

<script src="myscript.js">

Using JavaScript to Access HTML Elements

Bad HTML formatting may cause JavaScript execution errors.

The following two JavaScript statements will output different results:

Example

var obj = getElementById("Demo")

var obj = getElementById("demo")

Try It Yourself »

Try to use the same naming rules for HTML and JavaScript.

Visit HTML(5) Style Guide。


File Extensions

HTML file extensions can be.html( or.htm)。

CSS file extension is.css 。

JavaScript file extension is.js 。


Use Lowercase File Names

Most web servers (Apache, Unix) are case-sensitive: london.jpg cannot be accessed via London.jpg.

Other web servers (Microsoft, IIS) are case-insensitive: london.jpg can be accessed via London.jpg or london.jpg.

You must maintain a consistent style, and we recommend using lowercase file names throughout.

Other Extensions