Best practices for front-end code standards: Javascript

Source: Internet
Author: User

Preface

I have been refactoring the front-end code of the project recently and have also referred to the best practices of various front-end code to make front-end HTML, CSS, and JavaScript code more standard-compliant and better performance, with better maintainability, I have tasted the sweetness of restructuring, and I have also come up with the idea of writing this series of blogs. Front-end code has its inherent flexibility, which leads to the current chaotic front-end code situation. This series of articles hope to play a leading role, let more people pay attention to the quality of front-end code and write more standard front-end code.

There are three articles in this series, discussing HTML, CSS, and Javascript respectively. This article will discuss Javascript.

Javascript is a highly flexible scripting language, which provides a variety of writing methods for the same functions implemented by it. If there is no unified specification in the project, it will make javascript code difficult to maintain. As the project goes deeper, performance j is getting worse and files are getting bigger and bigger. Therefore, it is necessary to develop a unified coding specification as soon as possible. The following are some javascript specifications for your reference.

(1) encoding format

Different people have different opinions on the correct encoding format, but a unified format must be provided for the same project. The following are common encoding formats:

1. indent: tab (\ 0x09) is not used for indentation. Four spaces are used as logical indentation.

2. The left curly braces should end with a row instead of a single row. You should always use curly brackets to enclose logical blocks. Even if the logic is only one line, curly brackets should be used to enclose the blocks, which improves the readability of the Code. For example:

for (var i=0; i<100; i++) {     doSomething(i); }if (statement) {    doSomeThing;} else {    doSomeThing;}

3. Use single quotes to define strings. Javascript can use single or double quotation marks to define strings. However, javascript often contains html code because the attribute values of elements in html use double quotation marks, therefore, the use of single quotes for string definition is also convenient for html code containing double quotes inside the string.

var content = '<span id="spanid">…';

4. Note: If the comment does not occupy multiple rows, we recommend that you use // instead of/**/. The comment should only occupy one row instead of the right of the same line as the code.

5. Space: space is used to improve code readability. A space is used after the comma of the function parameter and before and after the operator,

doSomething(myChar, 0, 1);while (x === y)

6. semicolon: to end a statement, you must use a semicolon to avoid js compilation errors when compressing JavaScript code, because all spaces and carriage returns are deleted during compression.

(2) Naming rules

The standard naming rules are followed to improve code readability. A good name itself is a good comment.

1. Case sensitivity: currently, javascript object-oriented programming is more popular, so there will be a public or private concept. The principle is that the first letter of the public interface name is capitalized, and the first letter of the private interface name is lowercase.

2. Naming: Do not use abbreviations. Naming should describe the meaning rather than the type. Do not use the prefix of the identification type.

Not recommended

getWinfunction doSomething(str,  integer) {     ... ...}function doSomething(strMessage,  intLength) {     ...  ...}

Correct Name

getWindowfunction doSomething(message, length) {    ...  ...}
(3) programming specifications

The javascript programming specification is related to the code performance and the code is concise.

1. variable definition

Variable definition uses the keyword var. Not required. Do not use global variables. This reduces unnecessary variable definition queries. The variable should have an initial value or be set to null. Avoid the use of the keyword with, with performance is poor. Define variables in a centralized manner to reduce the amount of code.

var counter = 0, empty = null;

2. Function Definition

The function should be defined before it is used. The function should be defined after the variable. Reduce the number of global functions defined. The function is defined as immediate execution. brackets should be used to include the function definition body, which is readable.

var statement.function outer(c, d) {    var e = c * d;    function inner(a, b) {        return (e * a) + b;    }    return inner(0, 1);}var collection = (function () {    var keys = [], values = [];    return {        get: function () {            ......        }    };}());

3. The function alias should be used for multiple calls. For example, if a function is called multiple times in a loop, a function alias should be defined to reduce the jump of the call range chain and improve the performance.

function doSomething() {    var get = getDataByIndex;     for (var counter = 0; counter < 10000; counter++) {        var current = get(counter);        // ...    }}

4. Use strict comparison operators to reduce type conversion operations.

if (x === 5 && y !== 4)

5. Loop and Recursion: Try to put operations with poor performance outside the loop. Pre-calculate the value to be used in the loop. When there are multiple loops in the context, define a unified loop variable to avoid variable meaningless multiple definitions.

Error Code

// example 1for (var counter = 0; counter < 10000; counter++) {    try {       doSomething();    } catch (e) {    alert('Failure: ' + e);        break;    }}// example 2for (var counter = 0;counter < document.getElementsByTagName('div').length;counter++) {    doSomething();}// example 3for (var counter = 0; counter < 10; counter++) {    doSomething1();};for (var counter = 0; counter < 10; counter++) {    doSomething2();};

Correct Encoding

// example 1 try {    for (var counter = 0; counter < 10000; counter++) {         doSomething();     }} catch (e) {    alert('Failure: ' + e);}// example 2var target = document.getElementsByTagName('div').length;for (var counter = 0;counter < target ;counter++) {    doSomething();}// example 3var counter = 0;for (counter = 0; counter < 10; counter++) {    doSomething1();};for (counter = 0; counter < 10; counter++) {    doSomething2();};

6. Dom operations: Reduce the number of DOM tree updates, and merge DOM tree updates as much as possible to improve performance. Reduce the number of times the value is assigned to innerhtml. Avoid assigning values to the expando attribute on DOM objects to reduce possible memory leaks.

7. Use global variables and Methods: Avoid Eval, which is very performance-consuming. If you want to use a global variable or method, you should add a window to reduce the context definition search.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.