Code specification We should follow the old principle that “just because you can doesn’t mean you should”.

Global namespace pollution

Always wrap the code in an immediate function expression, forming a separate module.

Is not recommended

var x = 10,
    y = 100;
console.log(window.x + ' ' + window.y);Copy the code
; (function(window){ 'use strict'; var x = 10, y = 100; console.log(window.x + ' ' + window.y); }(window));Copy the code

Execute function immediately

In the immediate execution of the function, if useful to the global variable should be passed through the variable, so that the immediate execution of the function body when called, can be called in the form of local variables, to a certain extent, improve the performance of the program. And you should add undefined to the immediate function’s parameter at the last position. This is because in ES3 undefined is read and write, and if you change the value of undefined in the global position, your code may not get overdue results. In addition, it is recommended to add semicolons at the beginning and end of the immediately executed function, so as to prevent the merge from affecting our own code because other people’s code is not standard

(function(){
    'use strict';
    var x = 10,
        y = 100,
        c,
        elem=$('body');
    console.log(window.x + ' ' + window.y);
    $(document).on('click',function(){

    });
    if(typeof c==='undefined'){
        //你的代码
    }
}());Copy the code
; (function($,window,document,undefined){ 'use strict'; var x = 10, y = 100, c, elem=$('body'); console.log(window.x + ' ' + window.y); $(document).on('click',function(){ }); If (typeof c==='undefined'){// your code}}(jQuery,window,document);Copy the code

Strict mode

ECMAScript 5 strict mode can be activated throughout the script or within a single method. It does more rigorous error checking for different javascript contexts. Strict mode also ensures that javascript code is more robust and runs faster.

Strict mode prevents the use of reserved keywords that are likely to be introduced in the future.

You should enable strict mode in your scripts, preferably in separate, immediately executed functions. Avoid using it on the first line of your script and causing all of your scripts to start in strict mode, which can cause problems with third-party libraries. Is not recommended

'use strict';
(function(){

}());Copy the code
(function(){ 'use strict'; } ());Copy the code

Variable declarations

For all variable declarations, we should specify var. If var is not specified, an error will be reported in strict mode, and variables in the same scope should be declared with one var, separated by a comma (,). Is not recommended

function myFun(){
    x=5;
    y=10;
}Copy the code

Incomplete recommendation

function myFun(){
    var x=5;
    var y=10;
}Copy the code
function myFun(){
    var x=5,
        y=10;
}Copy the code

Use comparative judgment with type judgment

Always use the === exact comparison operator to avoid the hassle of JavaScript casts in the judgment process.

If you use the === operator, the comparison must be of the same type. Is not recommended

(function(w){
  'use strict';

  w.console.log('0' == 0); // true
  w.console.log('' == false); // true
  w.console.log('1' == true); // true
  w.console.log(null == undefined); // true

  var x = {
    valueOf: function() {
      return 'X';
    }
  };

  w.console.log(x == 'X');//true

}(window.console.log));Copy the code
(function(w){
  'use strict';

  w.console.log('0' === 0); // false
  w.console.log('' === false); // false
  w.console.log('1' === true); // false
  w.console.log(null === undefined); // false

  var x = {
    valueOf: function() {
      return 'X';
    }
  };

  w.console.log(x === 'X');//false

}(window));Copy the code

The logical operation when assigning a value to a variable

Logical operators | | and && can also be used to return a Boolean value. If the object is not a Boolean, each expression is checked from left to right. Based on this operation, one expression is always returned eventually. This can be used to simplify your code when assigning values to variables. Is not recommended

if(! x) { if(! y) { x = 1; } else { x = y; }}Copy the code
x = x || y || 1;Copy the code

A semicolon

Always use semicolons, because implicit code nesting can cause hidden problems. Of course, we should put an end to these problems fundamentally [1]. The following examples show the dangers of missing semicolons:

// 1. MyClass.prototype.myMethod = function() { return 42; } function() {})(); Var x = {' I ': 1, 'j': 2}; var x = {' I ': 1, 'j': 2}; / / 3. Var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] / / there is no semicolon - 1 = = resultOfOperation () | | die ();Copy the code

Incorrect results

  1. JavaScript error – the function that first returns 42 is called with an argument passed in from the second function, and the number 42 is “called” as well.

  2. You’ll probably get ‘no such property in undefined’ because in the real world the call would look like this: xffVersion, ieVersion().

  3. Die is always called. Because the array minus one results in a NaN, it doesn’t equal anything (whether resultOfOperation returns a NaN or not). So the end result is that when die() completes, the value is assigned to THINGS_TO_EAT.

A function declaration within a statement block

Do not declare functions inside a block; this is illegal under ECMAScript 5’s strict mode. Function declarations should be at the top level of the scope. However, function declarations can be converted into function expressions and assigned to variables within a statement block. Is not recommended

if (x) {
  function foo() {}
}Copy the code
if (x) {
  var foo = function() {};
}Copy the code

Do not use the eval function

Eval () is contextually confusing and dangerous. There is always a better, clearer, and safer way to write your code, so try not to use eval.

Array and object literals

1. Replace arrays and object constructors with array and object literals. The array constructor makes it easy to make mistakes with its arguments.

Is not recommended

Var a1 = new Array(x1, x2, x3); Var a2 = new Array(x1, x2); Var a3 = new Array(x1); // If x1 is a natural number, its length will be 1. var a4 = new Array();Copy the code

Because of this, if you change the code parameters from two to one, the array is likely to have unexpected length changes. To avoid such quirks, always use readable array literals. recommended

var a = [x1, x2, x3];
var a2 = [x1, x2];
var a3 = [x1];
var a4 = [];Copy the code

2. Object constructors do not have similar problems, but for readability and consistency, object literals should be used.

Is not recommended

var o = new Object();

var o2 = new Object();
o2.a = 0;
o2.b = 1;
o2.c = 2;
o2['strange key'] = 3;Copy the code
var o = {};
var o2 = {
  a: 0,
  b: 1,
  c: 2,
  'strange key': 3
};Copy the code

Ternary conditional judgment (quick method for if)

Allocates or returns statements with ternary operators. Use in simple situations and avoid complex ones. No one wants to wrap their heads around 10-line ternary operators. Is not recommended

if(x === 10) {
  return 'valid';
} else {
  return 'invalid';
}Copy the code
return x === 10 ? 'valid' : 'invalid';Copy the code

The for loop

When using a for loop, the length of the array is received using a variable, which is a good way to improve code execution efficiency, rather than having to recalculate the array length every time you go through the loop

for(var i=0; iCopy the code

for(var i=0,len=arr.length; iCopy the code

Repeated DOM operations

Repeated DOM operations, where it is necessary to use a variable for receiving rather than frequently manipulating the DOM tree, are undesirable for performance and for code cleanliness and maintainability

$('.myDiv').find('.span1').text('1');
$('.myDiv').find('.span2').text('2');
$('.myDiv').find('.span3').text('3');
$('.myDiv').find('.span4').text('4');Copy the code
var mydiv=$('.myDiv');
mydiv.find('.span1').text('1');
mydiv.find('.span2').text('2');
mydiv.find('.span3').text('3');
mydiv.find('.span4').text('4');Copy the code

End () is recommended if jquery.end () is available

$('.myDiv').find('.span1').text('1')
           .end().find('.span2').text('2');
           .end().find('.span3').text('3');
           .end().find('.span4').text('4');Copy the code

Annotation specifications

A formatted and consistent comment style is recommended when describing comments, and try to describe how the code was written rather than what the code did. Is not recommended

Function getOrderByID(id){var order; / /... return order; }Copy the code

Method annotations should be uniformly recommended with block-level annotations

* @param {[number]} id [order] * @return {[order]} [order] */ function getOrderByID(id){var order;  / /... return order; }Copy the code