First, naming rules

1. Project naming

Use all lowercase letters and delimit by underscore.

Example: my_project_name

2. Name the directory

Refer to project naming rules;

When there is a complex number structure, use the plural nomenclature.

Examples: scripts, styles, images, data_models

3. Name the JS file

Refer to the project naming rules.

Example: account_model. Js

4. CSS, SCSS file name

Refer to the project naming rules.

Example: retina_sprites SCSS

5. Name the HTML file

Refer to the project naming rules.

Example: error_report. HTML

Second, the HTML

1. Grammar

Indent using soft TAB (4 Spaces);

Nested nodes should be indented;

On attributes, use double quotes, not single quotes;

Attribute names are all lowercase, delimited by hyphens.

Don’t use slashes at the end of auto-closing tags (the HTML5 specification states that they are optional);

Do not omit optional closing tags, such as and.

<! DOCTYPE html> <html> <head> <title>Page title</title> </head> <body> <img src="images/company_logo.png" alt="Company">

        <h1 class="hello-world">Hello, world! </h1> </body> </html>Copy the code

2. HTML5 doctype

Use this simple docType at the beginning of the page to enable standard mode, rendering it as consistently as possible across browsers;

Although docType is case insensitive, by convention, docType is uppercase (uppercase or lowercase for HTML attributes).

<! DOCTYPE html> <html> ... </html>Copy the code

3. The lang attribute

According to the HTML5 specification:

The LANG attribute should be attached to the HTML tag. This will help voice tools and translation tools tell them how to pronounce and translate. More on lang properties are explained here;

You can find a list of languages on SitePoint;

However, Sitepoint only gives the language categories, for example, Chinese only gives zh, but does not distinguish Between Hong Kong, Taiwan and mainland. Microsoft has a more detailed list, which breaks down zh-CN, zh-HK, and zh-TW.

<! DOCTYPE html> <html lang="en-us">... </html>Copy the code

4. Character encoding

Allows browsers to quickly and easily determine the appropriate rendering method for web content by declaring an explicit character encoding, usually specified as ‘UTF-8’.

<! DOCTYPE html> <html> <head> <meta charset="UTF-8">
    </head>
    ...
</html>
Copy the code

5. Compatible with Internet Explorer

The tag allows you to specify which version of IE the page should be rendered with;

If you want to learn more, click here;

Different doctypes trigger different rendering modes in different browsers (this article summarizes them nicely).

<! DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>
    ...
</html>
Copy the code

6. Introduce CSS, JS

According to the HTML5 specification, there is usually no need to specify type when importing CSS and JS, since text/ CSS and text/javascript are their default values, respectively.

HTML5 specification link

Use the link

Use the style

Use the script

<! -- External CSS --> <link rel="stylesheet" href="code_guide.css"> <! -- In-document CSS --> <style> ... </style> <! -- External JS --> <script src="code_guide.js"></script> <! -- In-document JS --> <script> ... </script>Copy the code

7. Attribute order

Attributes should appear in a specific order to ensure readability;

  • class
  • id
  • name
  • data-*
  • src, for, type, href, value , max-length, max, min, pattern
  • placeholder, title, alt
  • aria-*, role
  • required, readonly, disabled

Class is designed for highly reusable components and should come first;

Id is more specific and should be used sparingly, so it comes second.

<a class="..." id="..." data-modal="toggle" href="#">Example link</a>

<input class="form-control" type="text">

<img src="..." alt="...">
Copy the code

8. A Boolean attribute

Boolean attributes are attributes that do not require a value to be declared. XHTML requires a value for each attribute, but HTML5 does not.

WhatWG Section on Boolean Attributes for more information:

The Boolean property is true if it exists, false if it does not.

<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
    <option value="1" selected>1</option>
</select>
Copy the code

9.JS generates labels

Generating tags in JS files makes content harder to find, harder to edit, and worse performance. This should be avoided as much as possible.

10. Reduce the number of labels

When writing HTML code, you need to avoid redundant parent nodes;

Many times, you need to iterate and refactor to make HTML less.

<! -- Not well --> <span class="avatar">
    <img src="..."> </span> <! -- Better --> <img class="avatar" src="...">
Copy the code

11. Utility trumps perfection

Try to follow HTML standards and semantics, but not at the expense of usability;

Solve problems with as little complexity and as few tags as possible at all times.

Third, the CSS, SCSS

1. The indentation

Use soft TAB (4 Spaces).

.element {
    position: absolute;
    top: 10px;
    left: 10px;

    border-radius: 10px;
    width: 50px;
    height: 50px;
}
Copy the code

2. A semicolon

Each property declaration ends with a semicolon.

.element {
    width: 20px;
    height: 20px;

    background-color: red;
}
Copy the code

3. The space

Spaces are not required in the following cases:

  • The property name after
  • Multiple rule delimiters before ‘,’
  • ! important ‘! After the ‘
  • Property value before ‘(‘ after and ‘)’
  • Don’t have extra space at the end of the line

Spaces are required in the following cases:

  • Attribute values before
  • Selectors ‘>’, ‘+’, ‘~’ before and after
  • ‘{‘ before
  • ! important ‘! Before ‘
  • Before and after the @ the else
  • Property value after ‘,’
  • Comments’ /‘and’Before/’
/* not good */ .element { color :red! important; Background - color: rgba (0, 0, 5); } /* good */ .element { color: red ! important; background-color: rgba(0, 0, 0, .5); } /* not good */ .element , .dialog{ ... } /* good */ .element, .dialog { } /* not good */ .element>.dialog{ ... } /* good */ .element > .dialog{ ... } /* not good */ .element{ ... } /* good */ .element { ... } /* not good */ @if{
    ...
}@else{... } /* good */ @if{... } @else{... }Copy the code

4. A blank line

Blank lines are required in the following cases:

  • Leave a blank line at the end of the file
  • ‘}’ should be followed by a blank line, including nested rules in SCSS
  • Appropriate blank lines are required between attributes, as described in attribute declaration order
/* not good */ .element { ... } .dialog { color: red; &:after { ... } } /* good */ .element { ... } .dialog { color: red; &:after { ... }}Copy the code

5. Line breaks

Line breaks are not required in the following cases:

A line break is required in the following cases before ‘{‘ :

Element {color: red; /* not good */. Element {color: red; background-color: black; }

/* good */ .element { color: red; background-color: black; }

/* not good */ .element, .dialog { … }

/* good */ .element, .dialog { … }

6. Comment

Use ‘/* */’ for comments (SCSS also do not use ‘//’), refer to the right side of the notation;

Indent the same as the next line of code;

Can be at the end of a line of code, separated by a space from the code.

/* Modal header */
.modal-header {
    ...
}

/*
 * Modal header
 */
.modal-header {
    ...
}

.modal-header {
    /* 50px */
    width: 50px;

    color: red; /* color red */
}
Copy the code

7. Quotes

Use double quotation marks on the outermost layer;

The content of the URL should be quoted;

Attribute values in attribute selectors need quotes.

.element:after {
    content: "";
    background-image: url("logo.png");
}

li[data-type="single"] {... }Copy the code

Named after 8.

  • Class names are lowercase letters separated by hyphens
  • The ID is named in camel shape
  • Variables, functions, mixers, placeholder in SCSS are named in camel shape
/* class */
.element-content {
    ...
}

/* id */
#myDialog {. } /* Variable */$colorBlack: # 000;/* Function */ @function pxToRem($px) {... } /* mixin */ @mixin centerBlock {... } /* placeholder */ %myDialog { ... }Copy the code

9. Order of attribute declaration

Related attribute declarations are grouped in the order on the right, with a blank line between the groups.

.declaration-order {
    display: block;
    float: right;

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;

    border: 1px solid #e5e5e5;
    border-radius: 3px;
    width: 100px;
    height: 100px;

    font: normal 13px "Helvetica Neue", sans-serif; The line - height: 1.5; text-align: center; color:# 333;
    background-color: #f5f5f5;opacity: 1; } // Here is the order of recommended attributes [["display"."visibility"."float"."clear"."overflow"."overflow-x"."overflow-y"."clip"."zoom"
    ],
    [
        "table-layout"."empty-cells"."caption-side"."border-spacing"."border-collapse"."list-style"."list-style-position"."list-style-type"."list-style-image"
    ],
    [
        "-webkit-box-orient"."-webkit-box-direction"."-webkit-box-decoration-break"."-webkit-box-pack"."-webkit-box-align"."-webkit-box-flex"
    ],
    [
        "position"."top"."right"."bottom"."left"."z-index"
    ],
    [
        "margin"."margin-top"."margin-right"."margin-bottom"."margin-left"."-webkit-box-sizing"."-moz-box-sizing"."box-sizing"."border"."border-width"."border-style"."border-color"."border-top"."border-top-width"."border-top-style"."border-top-color"."border-right"."border-right-width"."border-right-style"."border-right-color"."border-bottom"."border-bottom-width"."border-bottom-style"."border-bottom-color"."border-left"."border-left-width"."border-left-style"."border-left-color"."-webkit-border-radius"."-moz-border-radius"."border-radius"."-webkit-border-top-left-radius"."-moz-border-radius-topleft"."border-top-left-radius"."-webkit-border-top-right-radius"."-moz-border-radius-topright"."border-top-right-radius"."-webkit-border-bottom-right-radius"."-moz-border-radius-bottomright"."border-bottom-right-radius"."-webkit-border-bottom-left-radius"."-moz-border-radius-bottomleft"."border-bottom-left-radius"."-webkit-border-image"."-moz-border-image"."-o-border-image"."border-image"."-webkit-border-image-source"."-moz-border-image-source"."-o-border-image-source"."border-image-source"."-webkit-border-image-slice"."-moz-border-image-slice"."-o-border-image-slice"."border-image-slice"."-webkit-border-image-width"."-moz-border-image-width"."-o-border-image-width"."border-image-width"."-webkit-border-image-outset"."-moz-border-image-outset"."-o-border-image-outset"."border-image-outset"."-webkit-border-image-repeat"."-moz-border-image-repeat"."-o-border-image-repeat"."border-image-repeat"."padding"."padding-top"."padding-right"."padding-bottom"."padding-left"."width"."min-width"."max-width"."height"."min-height"."max-height"
    ],
    [
        "font"."font-family"."font-size"."font-weight"."font-style"."font-variant"."font-size-adjust"."font-stretch"."font-effect"."font-emphasize"."font-emphasize-position"."font-emphasize-style"."font-smooth"."line-height"."text-align"."-webkit-text-align-last"."-moz-text-align-last"."-ms-text-align-last"."text-align-last"."vertical-align"."white-space"."text-decoration"."text-emphasis"."text-emphasis-color"."text-emphasis-style"."text-emphasis-position"."text-indent"."-ms-text-justify"."text-justify"."letter-spacing"."word-spacing"."-ms-writing-mode"."text-outline"."text-transform"."text-wrap"."-ms-text-overflow"."text-overflow"."text-overflow-ellipsis"."text-overflow-mode"."-ms-word-wrap"."word-wrap"."-ms-word-break"."word-break"
    ],
    [
        "color"."background"."filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"."background-color"."background-image"."background-repeat"."background-attachment"."background-position"."-ms-background-position-x"."background-position-x"."-ms-background-position-y"."background-position-y"."-webkit-background-clip"."-moz-background-clip"."background-clip"."background-origin"."-webkit-background-size"."-moz-background-size"."-o-background-size"."background-size"
    ],
    [
        "outline"."outline-width"."outline-style"."outline-color"."outline-offset"."opacity"."filter:progid:DXImageTransform.Microsoft.Alpha(Opacity"."-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha"."-ms-interpolation-mode"."-webkit-box-shadow"."-moz-box-shadow"."box-shadow"."filter:progid:DXImageTransform.Microsoft.gradient"."-ms-filter:\\'progid:DXImageTransform.Microsoft.gradient"."text-shadow"
    ],
    [
        "-webkit-transition"."-moz-transition"."-ms-transition"."-o-transition"."transition"."-webkit-transition-delay"."-moz-transition-delay"."-ms-transition-delay"."-o-transition-delay"."transition-delay"."-webkit-transition-timing-function"."-moz-transition-timing-function"."-ms-transition-timing-function"."-o-transition-timing-function"."transition-timing-function"."-webkit-transition-duration"."-moz-transition-duration"."-ms-transition-duration"."-o-transition-duration"."transition-duration"."-webkit-transition-property"."-moz-transition-property"."-ms-transition-property"."-o-transition-property"."transition-property"."-webkit-transform"."-moz-transform"."-ms-transform"."-o-transform"."transform"."-webkit-transform-origin"."-moz-transform-origin"."-ms-transform-origin"."-o-transform-origin"."transform-origin"."-webkit-animation"."-moz-animation"."-ms-animation"."-o-animation"."animation"."-webkit-animation-name"."-moz-animation-name"."-ms-animation-name"."-o-animation-name"."animation-name"."-webkit-animation-duration"."-moz-animation-duration"."-ms-animation-duration"."-o-animation-duration"."animation-duration"."-webkit-animation-play-state"."-moz-animation-play-state"."-ms-animation-play-state"."-o-animation-play-state"."animation-play-state"."-webkit-animation-timing-function"."-moz-animation-timing-function"."-ms-animation-timing-function"."-o-animation-timing-function"."animation-timing-function"."-webkit-animation-delay"."-moz-animation-delay"."-ms-animation-delay"."-o-animation-delay"."animation-delay"."-webkit-animation-iteration-count"."-moz-animation-iteration-count"."-ms-animation-iteration-count"."-o-animation-iteration-count"."animation-iteration-count"."-webkit-animation-direction"."-moz-animation-direction"."-ms-animation-direction"."-o-animation-direction"."animation-direction"
    ],
    [
        "content"."quotes"."counter-reset"."counter-increment"."resize"."cursor"."-webkit-user-select"."-moz-user-select"."-ms-user-select"."user-select"."nav-index"."nav-up"."nav-right"."nav-down"."nav-left"."-moz-tab-size"."-o-tab-size"."tab-size"."-webkit-hyphens"."-moz-hyphens"."hyphens"."pointer-events"]]Copy the code

Color 10.

Color hexadecimal lowercase letters;

Use abbreviations for hexadecimal colors.

/* not good */
.element {
    color: #ABCDEF;
    background-color: # 001122;
}

/* good */
.element {
    color: #abcdef;
    background-color: # 012;
}
Copy the code

11. Property shorthand

Property abbreviations require you to be very clear about the correct order of property values, and in most cases you do not need to set all the values contained in property abbreviations, so separate declarations are recommended to be clearer;

Margin, as opposed to padding, needs to be abbreviated;

Common property abbreviations include:

  • font
  • background
  • transition
  • animation
/* not good */
.element {
    transition: opacity 1s linear 2s;
}

/* good */
.element {
    transition-delay: 2s;
    transition-timing-function: linear;
    transition-duration: 1s;
    transition-property: opacity;
}
Copy the code

12. Media enquiries

Try to keep the rules for media queries close to the rules related to them, and don’t put them together in a separate style file or at the bottom of the document, which only makes it easier for people to forget them later.

.element { ... } .element-avatar{ ... } @media (min-width: 480px) { .element { ... } .element-avatar { ... }}Copy the code

13. SCSS related

Do not submit code with @debug;

Declaration order:

  • @extend
  • At sign include without at sign content
  • At sign include with at sign content
  • Its properties
  • The nesting rule @import introduces files that do not need to start with ‘_’ and end with ‘.scss’;

The nesting cannot exceed 5 layers;

Placeholder selectors are used in @extend;

Remove unnecessary parent reference symbol ‘&’.

/* not good */
@import "_dialog.scss";

/* good */
@import "dialog"; /* not good */ .fatal { @extend .error; } /* good */ .fatal { @extend %error; } /* not good */ .element { & > .dialog { ... } } /* good */ .element { > .dialog { ... }}Copy the code

14. Miscellaneous

The rule of not being available;

Element selectors are lowercase;

Remove the 0 in front of the decimal point;

Remove unnecessary decimal points and trailing zeros from numbers;

Attribute value ‘0’ is not followed by a unit;

Different prefixes for the same attribute should be aligned vertically, as shown on the right;

Standard attributes without prefixes should be written after prefixed attributes;

Do not have duplicate attributes in the same rule. It does not matter if the repeated attributes are contiguous.

Don’t have two rules in the same file;

With the border: 0; Instead of the border: none; ;

No more than 4 layers of selectors (in SCSS if more than 4 layers should be considered nested);

Don’t publish code with @import;

Use the ‘*’ selector as little as possible.

/* not good */ .element { } /* not good */ LI { ... } /* good */ li { ... } /* not good */. Element {color: rgba(0, 0, 0, 0.5); } /* good */ .element { color: rgba(0, 0, 0, .5); } /* Not good */. Element {width: 50.0px; } /* good */ .element { width: 50px; } /* not good */ .element { width: 0px; } /* good */ .element { width: 0; } /* not good */ .element { border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; background: linear-gradient(to bottom,#fff 0, #eee 100%);
    background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
    background: -moz-linear-gradient(top, #fff 0, #eee 100%);
}

/* good */
.element {
    -webkit-border-radius: 3px;
       -moz-border-radius: 3px;
            border-radius: 3px;

    background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
    background:    -moz-linear-gradient(top, #fff 0, #eee 100%);
    background:         linear-gradient(to bottom, #fff 0, #eee 100%);
}

/* not good */
.element {
    color: rgb(0, 0, 0);
    width: 50px;
    color: rgba(0, 0, 0, .5);
}

/* good */
.element {
    color: rgb(0, 0, 0);
    color: rgba(0, 0, 0, .5);
}
Copy the code

Four, JavaScript,

1. The indentation

Use soft TAB (4 Spaces).

var x = 1,
    y = 1;

if (x < y) {
    x += 10;
} else {
    x += 1;
}
Copy the code

2. Single line length

Don’t exceed 80, but if the editor turns on Word Wrap, you can ignore the line length. A semicolon

A semicolon should be added in the following cases:

  • Variable declarations
  • expression
  • return
  • throw
  • break
  • continue
  • do-while
/* var declaration */ var x = 1; /* expression statement */ x++; / *do-while */
do {
   x++;
} while (x < 10);
Copy the code

3. The space

Spaces are not required in the following cases:

  • Object after the property name
  • Prefixes unary operator after
  • Suffix before unary operator
  • Function call before parentheses
  • Do not precede the ‘(‘ in function declarations or expressions
  • Array after ‘[‘ and before ‘]’
  • Object after ‘{‘ and before ‘}’
  • Operators ‘(‘ after and ‘)’ before

Spaces are required in the following cases:

  • Binary operator before and after
  • The ternary operator ‘? Before and after: ‘
  • Code block ‘{‘ before
  • Before: else, while, catch, finally
  • After the following keywords: if, else, for, while, do, switch, case, try, catch, finally, with, return, typeof
  • Single-line comments after ‘//’ (if single-line comments are the same as code, ‘//’ is also required), multi-line comments after ‘*’
  • Object before the property value
  • For loop, a semicolon followed by a space, and a comma followed by a space if there are more than one preconditions
  • In function declarations and expressions, always precede the ‘{‘ with a space
  • Between the parameters of a function
// not good var a = { b :1 }; // good var a = { b: 1 }; // not good ++ x; y ++; z = x? 1:2; // good ++x; y++; z = x ? 1:2; // not good var a = [ 1, 2 ]; // good var a = [1, 2]; // not good var a = ( 1+2 )*3; // good var a = (1 + 2) * 3; // no space before'(', one space before '{', one space between function parameters
var doSomething = function(a, b, c) {
    // do something
};

// no space before '('
doSomething(item);

// not good
for(i=0; i<6; i++){ x++; } // goodfor (i = 0; i < 6; i++) {
    x++;
}
Copy the code

5. A blank line

Blank lines are required in the following cases:

  • After a variable is declared (blank lines are not required when the variable is declared on the last line of the code block)
  • Before the comment (blank lines are not required when the comment is on the first line of the code block)
  • After a block of code (no blank lines in function calls, arrays, objects)
  • Leave a blank line at the end of the file
// need blank line after variable declaration
var x = 1;

// not need blank line when variable declaration is last expression in the current block
if (x >= 1) {
    var y = x + 1;
}

var a = 2;

// need blank line before line comment
a++;

function b() {
    // not need blank line when comment is first line of block
    return a;
}

// need blank line after blocks
for (var i = 0; i < 2; i++) {
    if (true) {
        return false;
    }

    continue;
}

var obj = {
    foo: function() {
        return 1;
    },

    bar: function() {
        return2; }}; // not need blank line whenin argument list, array, object
func(
    2,
    function() { a++; }, 3); var foo = [ 2,function() { a++; }, 3); var foo = { a: 2, b:function() {
        a++;
    },
    c: 3
};
Copy the code

6. A line break

At the end of a line break there must be a ‘,’ or operator;

Line breaks are not required in the following cases:

  • Else, catch, finally
  • Code block ‘{‘ before

Line breaks are required in the following cases:

  • Code blocks ‘{‘ after and ‘}’ before
  • After the variable is assigned
// not good var a = { b: 1 , c: 2 }; x = y ? 1:2; // good var a = { b: 1, c: 2 }; x = y ? 1:2; x = y ? 1:2; // no need linebreak with 'else'.'catch'.'finally'
if (condition) {
    ...
} else{... } try { ... } catch (e) { ... } finally { ... } // not goodfunction test() {... } // goodfunction test() {... } // not good var a, foo = 7, b, c, bar = 8; // good var a, foo = 7, b, c, bar = 8;Copy the code

7. One-line comments

A double slash must be followed by a space;

Indent the same as the next line of code;

Can be at the end of a line of code, separated by a space from the code.

if (condition) {
    // if you made it here, then all security checks passed
    allowed();
}

var zhangsan = 'zhangsan'; // one space after code
Copy the code

8. Multi-line comments

At least three lines with ‘*’ followed by a space, as shown on the right;

It is recommended to be used in the following situations:

  • Difficult code snippets
  • There may be incorrect code snippets
  • Browser-specific HACK code
  • Code with strong business logic correlation
/*
 * one space after The '*'
 */
var x = 1;
Copy the code

9. Document notes

Please refer to usEJsDoc and JSDoc Guide for tags @param, @Method, etc.

It is recommended to be used in the following situations:

  • All of the constants
  • All the functions
  • All the classes
/** * @func * @desc A function with arguments * @param {string} a - parameter a * @param {number} b=1 - Parameter b default value is 1 * @param {string} c=1 - There are two supported values for parameter C: </br>1 - x</br>2 - XX * @param {object} d - Parameter D is an object * @param {string} d.e - The e attribute of parameter D * @param {string} d.f - Parameter d f attribute * @param {object[]} g - parameter g is an object array * @param {string} g.h - parameter g array h attribute * @param {string} g.i - parameter g array I attribute * @param {string} [j] - Argument j is an optional argument */function foo(a, b, c, d, g, j) {
    ...
}
Copy the code

10. Quotes

Use single quotation marks for the outermost layer.

// not good
var x = "test";

// good
var y = 'foo',
    z = '<div id="test"></div>';
Copy the code

11. Variable naming

  • Standard variables are named in camel case (in addition to the attributes of the object, the main consideration is the data returned by CGI)
  • ‘ID’ is all uppercase in the variable name
  • ‘URL’ is all uppercase in the variable name
  • ‘Android’ capitalizes the first letter in the variable name
  • ‘iOS’ is the first letter in the variable name, followed by two uppercase letters
  • Constants are all uppercase and underlined
  • Constructor, uppercase the first letter
  • Jquery objects must be named starting with ‘$’
var thisIsMyName;

var goodID;

var reportURL;

var AndroidVersion;

var iOSVersion;

var MAX_COUNT = 10;

function Person(name) {
    this.name = name;
}

// not good
var body = $('body');

// good
var $body = $('body');
Copy the code

Variable declarations

All variable declarations in a function scope refer to the header of the function as much as possible. Use a single var declaration.

function doSomethingWithItems(items) {
    // use one var
    var value = 10,
        result = value + 10,
        i,
        len;

    for(i = 0, len = items.length; i < len; i++) { result += 10; }}Copy the code

Function of 13.

In function declarations and expressions, there is no space before ‘(‘, but there must be a space before ‘{‘;

Function calls do not require Spaces before parentheses;

Immediate functions must be wrapped in parentheses;

Do not name inline functions;

// no space before '(', but one space before'{'
            var doSomething = function(item) {
    // do something
};

function doSomething(item) {
    // do something
}

// not good
doSomething (item);

// good
doSomething(item);

// requires parentheses around immediately invoked function expressions
(function() {
    return1; }) (); // not good [1, 2].forEach(function x() {... }); // good [1, 2].forEach(function() {... }); // not good var a = [1, 2,function a() {... }]; // good var a = [1, 2,function() {... }]; // use', ' between function parameters
var doSomething = function(a, b, c) {
    // do something
};
Copy the code

14. Arrays, objects

Object attribute names do not need to be quoted;

Write objects indented, not on a single line;

Arrays and objects should not end with commas.

// not good
var a = {
    'b': 1}; var a = {b: 1}; var a = { b: 1, c: 2, }; // good var a = { b: 1, c: 2 };Copy the code

15. The brackets

Braces must follow the following keywords (even if the block is only one line) : if, else, for, while, do, switch, try, catch, finally, with.

// not good
if (condition)
    doSomething();

// good
if (condition) {
    doSomething();
}
Copy the code

16. null

Applicable scenarios:

  • Initialize a variable that may be assigned as an object in the future
  • Compare with an already initialized variable
  • Call to a function that takes an object as an argument
  • The return value of a function that returns an object

Not applicable scenarios:

  • Do not use null to determine if a function is called with or without arguments
  • Do not compare with uninitialized variables
// not good
function test(a, b) {
    if (b === null) {
        // not mean b is not supply
        ...
    }
}

var a;

if (a === null) {
    ...
}

// good
var a = null;

if (a === null) {
    ...
}
Copy the code

17. undefined

Never use undefined directly for variable judgments;

Use typeof and the string ‘undefined’ to determine variables.

// not good
if (person === undefined) {
    ...
}

// good
if (typeof person === 'undefined') {... }Copy the code

18. jshint

Use ‘= = =’, ‘! ==’ instead of ‘==’, ‘! = ‘;

HasOwnProperty = hasOwnProperty;

Do not add methods to the prototype of built-in objects, such as Array, Date;

Do not declare a variable in the inner scope code and then access a variable of the same name in the outer scope.

Do not use variables before declaring them;

Don’t just use constructors in a line of code; assign them to a variable;

Do not declare variables of the same name in the same scope;

Do not put parentheses in unnecessary places, for example: delete(a.b);

Do not use undeclared variables (global variables need to be added to the globals property of the.jshintrc file);

Don’t declare variables and leave them unused;

Don’t assign values where comparisons should be made;

The debugger should not appear in submitted code;

Do not have empty elements in the array;

Do not declare functions inside loops;

Do not use constructors like this, for example: new function () {… }, the new Object;

// not good
if (a == 1) {
    a++;
}

// good
if (a === 1) {
    a++;
}

// good
for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        // be sure that obj[key] belongs to the object and was not inherited
        console.log(obj[key]);
    }
}

// not good
Array.prototype.count = function(value) {
    return 4;
};

// not good
var x = 1;

function test() {
    if (true) {
        var x = 0;
    }

    x += 1;
}

// not good
function test() {
    console.log(x);

    var x = 1;
}

// not good
new Person();

// good
var person = new Person();

// not good
delete(obj.attr);

// good
delete obj.attr;

// not good
if (a = 10) {
    a++;
}

// not good
var a = [1, , , 2, 3];

// not good
var nums = [];

for (var i = 0; i < 10; i++) {
    (function(i) {
        nums[i] = function(j) {
            return i + j;
        };
    }(i));
}

// not good
var singleton = new function() {
    var privateVar;

    this.publicMethod = function() {
        privateVar = 1;
    };

    this.publicMethod2 = function() {
        privateVar = 2;
    };
};
Copy the code

19. Miscellaneous

Don’t mix tabs and Spaces;

Don’t use multiple tabs or Spaces in one place;

Use ‘LF’ for line breaks;

References to context this can only be named ‘_this’, ‘that’, or ‘self’;

No whitespace characters at the end of the line;

The switch’s falling through and no default cases must be specified in a comment.

Empty code blocks are not allowed.

// not good
var a   = 1;

function Person() {
    // not good
    var me = this;

    // good
    var _this = this;

    // good
    var that = this;

    // good
    var self = this;
}

// good
switch (condition) {
    case 1:
    case2:...break;
    case3:... // why fall throughcase4...break;
    // why no default
}

// not good with empty block
if (condition) {

}
Copy the code

The original link: http://alloyteam.github.io/CodeGuide/