JavaScript style guide
- Previous Page JS Debugging
- Next Page JS Best Practices
Always use the same code conventions for all your JavaScript projects.
JavaScript code conventions
Code conventions (Coding conventions) refer toProgramming style guidelines. These principles generally include:
- Rules for naming and declaring variables and functions
- Rules for using spaces, indentation, and comments
- Programming habits and guidelines
Code conventionsEnsure quality:
- Improve code readability
- Improve code maintainability
Code conventions can be written rules followed by a team or your personal coding habits.
This page introduces the general JavaScript code conventions used by CodeW3C.com.
You should continue reading the next chapter 'Best Practices' to learn how to avoid coding pitfalls.
variable names
On CodeW3C.com, we usecamelCase.
All names start withLettersStart.
At the bottom of this page, we will discuss naming conventions more broadly.
firstName = "Bill"; lastName = "Gates"; price = 19.90; tax = 0.20; fullPrice = price + (price * tax);
Spaces around operators
Always add a space around the operator (= + - * /) and after commas:
Example
var x = y + z; var values = ["Volvo", "Saab", "Fiat"];
Code indentation
Always use 4 spaces for indentation in code blocks:
Function
function toCelsius(fahrenheit) { return (5 / 9) * (fahrenheit - 32); }
Do not use tabs for indentation. Different editors may interpret tabs differently.
Statement rules
General rules for simple statements:
Always end a single statement with a semicolon:
Example
var values = ["Volvo", "Saab", "Fiat"]; var person = { firstName: "Bill", lastName: "Gates", age: 50, eyeColor: "blue" };
General rules for complex statements (compound):
- Write the opening bracket at the end of the first line;
- Use a space before the opening bracket;
- Write the closing bracket on a new line without leading spaces;
- Do not end complex statements with a semicolon;
Function:
function toCelsius(fahrenheit) { return (5 / 9) * (fahrenheit - 32); }
Loop:
for (i = 0; i < 5; i++) { x += i; }
Condition:
if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
Object rules
General rules for object definition:
- Place the opening bracket and the object name on the same line;
- Use a colon followed by a space between each property and its value;
- Do not write a comma after the last property value pair;
- Write the closing bracket on a new line without leading spaces;
- Always end the object definition with a semicolon;
Example
var person = { firstName: "Bill", lastName: "Gates", age: 19, eyeColor: "blue" };
The short object can be compressed on a single line, using spaces only between properties, like this:
var person = {firstName:"Bill", lastName:"Gates", age:50, eyeColor:"blue"};
Line length less than 80
To improve readability, avoid lines that exceed 80 characters in length.
If the JavaScript statement exceeds one line in length, the best place to break is after an operator or comma.
Example
document.getElementById("demo").innerHTML = "Hello Kitty.";
Naming conventions
Always use the same naming convention for all your code. For example:
- Variable and function names withCamelCaseto write
- Global variables useCapitalization(We do not do this, but it is quite common)
- Constants (such as PI) useCapitalization
Should we use in variable names?Hyphen,CamelCaseOrUnderscoreIs it?
This is a frequently discussed issue among programmers. The answer depends on who answers this question:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property names (font-size).
Hyphens can be mistakenly considered as subtraction operators. JavaScript naming does not allow the use of hyphens.
Underscore:
Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.
Underscores are often used in PHP references.
PascalCase:
C language programmers often use PascalCase.
CamelCase:
JavaScript itself, jQuery, and other JavaScript libraries use camelCase.
Please do not start JavaScript names with the $ symbol. This may cause name conflicts with JavaScript libraries.
Load JavaScript in HTML
Load external scripts using simple syntax (the type attribute is not required):
<script src="myscript.js"></script>
Access HTML elements
The consequence of using 'ugly' HTML styles may be causing JavaScript errors.
These two JavaScript statements will produce different results:
var obj = getElementById("Demo") var obj = getElementById("demo")
If possible, use the same naming convention in HTML (like JavaScript).
file extensions
HTML files should use .html Extensions (instead of .htm).
CSS files should use .css Extensions.
JavaScript files should use .js Extensions.
Use lowercase filenames
Most web servers (Apache, Unix) are case-sensitive for filenames:
london.jpg cannot be accessed as London.jpg.
Other web servers (Microsoft's IIS) are case-insensitive:
london.jpg can be accessed as London.jpg or london.jpg.
If you mix uppercase and lowercase, you must strictly maintain continuity and consistency.
If you move a site from a case-insensitive server to a case-sensitive server, even such small errors can break your website.
To avoid these issues, always use lowercase filenames (if possible).
Performance
Computers do not use coding conventions. Most rules have little impact on the execution of the program.
Indentation and extra spaces are not important for small scripts.
For scripts under development, readability should be given priority. Larger production scripts should be minimized.
- Previous Page JS Debugging
- Next Page JS Best Practices