1. Global namespace pollution
Always wrap the code in an immediate function expression to form an independent module.
Not recommended
var x = 10, y = 100;console.log(window.x + ' ' + window.y);
recommend
;(function(window){ 'use strict'; var x = 10, y = 100; console.log(window.x + ' ' + window.y);}(window));2. Execute the function immediately
In the immediate execution function, if global variables are used, the function body that executes the function immediately can be called in the form of local variables when called, which improves program performance to a certain extent.
And you should add undefined to the formal parameters of the function immediately, at the last position, because undefined in ES3 can be read and written. If the value of undefined is changed 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 function immediately to avoid affecting our own code due to irregular other people's code during merging.
Not recommended
(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'){ //Your code}}());recommend
;(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));3. Strict mode
ECMAScript 5 Strict mode can be activated throughout the script or within a single method. It corresponds to different javascript contexts and will perform more stringent error checks. Strict mode also ensures that the 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 script, preferably apply it in a standalone immediate execution function. Avoid using it on the first line of your script that causes all your scripts to start strict mode, which may cause problems with some third-party library.
Not recommended
'use strict';(function(){}());recommend
(function(){ 'use strict';}());IV. Variable declaration
For all variable declarations, we should specify var . If var is not specified, an error will be reported in strict mode, and variables within the same scope should be declared with one var as much as possible, and multiple variables should be separated by ",".
Not recommended
function myFun(){ x=5; y=10;}Not fully recommended
function myFun(){ var x=5; var y=10;}recommend
function myFun(){ var x=5, y=10;}5. Comparative judgment using type judgment
It uses the === exact comparison operator to avoid the trouble caused by JavaScript's cast during the judgment process.
If you use the === operator, the two parties to the comparison must be of the same type to be valid.
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));recommend
(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));6. Logical operations when variable assignment
Logical operators || and && can also be used to return boolean values. If the operation object is a non-Boolean object, then each expression will be judged from left to right. Based on this operation, there is always an expression that is returned in the end. This can be used to simplify your code when assigning variables.
Not recommended
if(!x) { if(!y) { x = 1; } else { x = y; }}recommend
x = x || y || 1;
7. Semi-colon
Always use semicolons because implicit code nesting can cause undetectable problems. Of course, we must fundamentally eliminate these problems [1].
The following examples show the harm of missing a semicolon:
// 1.MyClass.prototype.myMethod = function() { return 42;} // There is no semicolon here(function() {})(); //2.var x = { 'i': 1, 'j': 2} // There is no semicolon here//I know you may never write such a code, but I'll give an example [ffVersion, ieVersion][isIE](); // 3.var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // There is no semicolon here-1 == resultOfOperation() || die();Error results
1. JavaScript error - The function that returns 42 is called first by the parameter in the second function, and then the number 42 is also "called", resulting in an error.
2. Eighty times you will get the error message of 'no such property in undefined', because the call in the real environment looks like this: xffVersion, ieVersion().
3.die is always called. Because the result of minus 1 in the array is NaN, it does not equal anything (regardless of whether resultOfOperation returns NaN or not). So the final result is that the obtained value after die() is executed will be assigned to THINGS_TO_EAT.
8. Function declarations in statement blocks
Never declare functions within statement blocks, which is illegal in strict mode of ECMAScript 5. Function declarations should be at the top level of scope. However, within the statement block, the function declaration can be converted into a function expression and assigned to a variable.
Not recommended
if (x) { function foo() {}}recommend
if (x) { var foo = function() {};}9. Do not use eval function
eval() is not only confusing the context but also dangerous. There will always be another solution to write your code that is better, clearer and safer than this, so try not to use the eval function.
10. Array and object literals
1. Use array and object literals instead of array and object constructor. Array constructors can easily make mistakes on its parameters.
Not recommended
//Array length 3var a1 = new Array(x1, x2, x3);//Array length 2var a2 = new Array(x1, x2);//If x1 is a natural number, its length will be x1//If x1 is not a natural number, its length will be 1var a3 = new Array(x1);var a4 = new Array();
Because of this, if the code passes from two to one, there is a high possibility that the array will experience unexpected length changes. To avoid such weird situations, always use readable array literals.
recommend
var a = [x1, x2, x3];var a2 = [x1, x2];var a3 = [x1];var a4 = [];
2. The object constructor will not have similar problems, but for readability and uniformity, we should use object literals.
Not recommended
var o = new Object();var o2 = new Object();o2.a = 0;o2.b = 1;o2.c = 2;o2['strange key'] = 3;
recommend
var o = {};var o2 = { a: 0, b: 1, c: 2, 'strange key': 3};11. Triple-variable condition judgment (fast method for if)
Use the ternary operator to assign or return statements. Use in relatively simple situations and avoid using in complex situations. No one wants to use 10 lines of ternary operators to wiggle their minds.
Not recommended
if(x === 10) { return 'valid';} else { return 'invalid';}recommend
return x === 10 ? 'valid' : 'invalid';
12. For loop
During the process of using for loop, the length of the array is received by a variable, which is conducive to improving the code execution efficiency. Instead, the length of the array must be recalculated every time the loop is gone.
Not recommended
for(var i=0;i<arr.length,i++){}recommend
for(var i=0,len=arr.length;i<len,i++){}13. Repeated dom operations
Repeated dom operations, it is necessary to use a variable to receive, rather than frequently operating the dom tree, which has a bad impact on the performance, tidy code and easy maintenance.
Not recommended
$('.myDiv').find('.span1').text('1');$('.myDiv').find('.span2').text('2');$('.myDiv').find('.span3').text('3');$('.myDiv').find('.span4').text('4');recommend
var mydiv=$('.myDiv');mydiv.find('.span1').text('1');mydiv.find('.span2').text('2');mydiv.find('.span3').text('3');mydiv.find('.span4').text('4'); When jquery .end() is available, use .end() should be preferred.
recommend
$('.myDiv').find('.span1').text('1') .end().find('.span2').text('2'); .end().find('.span3').text('3'); .end().find('.span4').text('4');14. Comment specifications
When describing comments, a formatted and unified comment style is recommended. Try to describe the ideas when writing comments, rather than what the code does.
Not recommended
//Get order function getOrderByID(id){ var order; //... return order;}Method annotations should be uniformly used with block-level annotations
recommend
/** * Get order detailed data based on order id* @param {[number]} id [order ID] * @return {[order]} [order details] */function getOrderByID(id){ var order; //... return order;}Summarize
The summary of JavaScript's common code writing specifications is basically over. This article is still very comprehensive and has certain reference value for everyone to use or learn some Javascript. I hope it will be helpful to everyone. If you have any questions, you can leave a message to communicate.