Home >Web Front-end >JS Tutorial >15 JavaScript best practices summary_javascript tips

15 JavaScript best practices summary_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:26:161002browse

This document organizes most of the generally accepted, or less controversial, JavaScript best practices. Some obvious common sense will not be discussed (for example, use objects to support recognition judgments instead of browser recognition judgments; for example, do not nest too deeply). The items are sorted roughly from high to low importance.
Place external JavaScript files at the bottom of the HTML
Our goal is the same: display content as quickly as possible for the user. When loading a script file, HTML will stop parsing until the script is loaded. As a result, users may be looking at a blank screen for long periods of time, with nothing seemingly happening. If your JavaScript code just adds some functionality (such as a button click action), then feel free to put the file reference at the bottom of the HTML (just before ), and you will see a significant speed increase. If it is a script file used for other purposes, it needs to be carefully considered. Regardless, this is undoubtedly a place well worth considering.
Optimize loop
Loop through an array

Copy code The code is as follows:

//This bad code will calculate the length of the array every time it enters the loop
var names = ['George','Ringo','Paul','John'] ;
for(var i=0;idoSomeThingWith(names[i]);
}

Copy code The code is as follows:

//In this case, it will only be calculated once
var names = ['George' ,'Ringo','Paul','John'];
var all = names.length;
for(var i=0;idoSomeThingWith(names[i] );
}

Copy code The code is as follows: //This is shorter
var names = ['George','Ringo','Paul','John'];
for(var i=0,j=names.length;idoSomeThingWith(names[i]);
}




Copy code The code is as follows: //The bad thing about this code is that it puts the variable declaration in the loop body, and the variable will be created every time it loops
for(var i = 0; i < someArray.length; i ) {
var container = document.getElementById('container');
container.innerHtml = 'my number: ' i;
console.log(i);
}




Copy code The code is as follows: //In Declare variables outside the loop. Variables will only be created once
var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len; i ) {
container.innerHtml = 'my number: ' i;
console.log(i);
}



Use as short a code as possible

It makes sense to use short forms of code if it increases readability, here is a non-exhaustive list:

Copy code The code is as follows: //For conditional judgment only twice, this is a lengthy way of writing
var direction;
if(x > 100){
direction = 1;
} else {
direction = -1;
}




Copy code The code is as follows: //Better code
var direction = (x > 100) ? 1 : -1;




Copy code The code is as follows: //Judge whether a variable is defined, and if not, assign it to One value, bad code
if(v){
var x = v;
} else {
var x = 10;
}




Copy code The code is as follows: //Better code
var x = v || 10 ;


Copy code The code is as follows:

//Repeated variable name many times
var cow = new Object();
cow.colour = 'brown';
cow.commonQuestion = 'What now?';
cow.moo = function(){
console.log(' moo');
}
cow.feet = 4;
cow.accordingToLarson = 'will take over the world';

Copy code The code is as follows:

//A better way to write it is like this
var cow = {
colour:'brown',
commonQuestion:'What now?',
moo:function(){
console.log('moo);
},
feet:4,
accordingToLarson:'will take over the world'
};

Copy code The code is as follows:

//The array name is repeated many times
var aweSomeBands = new Array();
aweSomeBands[0] = 'Bad Religion';
aweSomeBands[1] = 'Dropkick Murphys';
aweSomeBands[2] = 'Flogging Molly';
aweSomeBands[3] = 'Red Hot Chili Peppers';
aweSomeBands[4] = 'Pornophonique';

Copy code The code is as follows:

//Better code
var aweSomeBands = [
' Bad Religion',
'Dropkick Murphys',
'Flogging Molly',
'Red Hot Chili Peppers',
'Pornophonique'
];

Single and double quotes
To avoid confusion, we recommend using double quotes in HTML and single quotes in JavaScript.
Copy code The code is as follows:

//html


Copy code The code is as follows:

//JavaScript


Copy code The code is as follows:

//A mixed jQuery code
$('h1 ').after('

Directory

    ');

    Avoid mixing other technologies
    CSS: Suppose there is an input box on our page that must be filled in (with class "mandatory"). If no data is entered into it, red will be added around it. frame.
    Copy code The code is as follows:

    //A piece of code mixed with other technologies will do this :
    var f = document.getElementById('mainform');
    var inputs = f.getElementsByTagName('input');
    for(var i=0,j=inputs.length;iif(inputs[i].className === 'mandatory' &&
    inputs[i].value === ''){
    inputs[i].style.borderColor = '#f00';
    inputs[i].style.borderStyle = 'solid';
    inputs[i].style.borderWidth = '1px';
    }
    }

    Copy code The code is as follows:

    //A good piece of code will do this: Leave the stylization to CSS
    var f = document.getElementById('mainform');
    var inputs = f.getElementsByTagName('input');
    for(var i=0,j= inputs.length;iif(inputs[i].className === 'mandatory' &&
    inputs[i].value === ''){
    inputs[ i].className = ' error';
    }
    }

    HTML: Suppose we have a lot of HTML content that needs to be loaded using JavaScript, then use Ajax to load separate files instead of processing the DOM through JavaScript. The latter will make the code difficult to process and cause compatibility that is difficult to maintain. question.
    Validate JavaScript code
    Browsers can be very forgiving when it comes to JavaScript code, but I advise you not to rely on the browser's parsing capabilities and therefore develop lazy coding habits.
    The easiest way to check the quality of your code is through JSLint, an online JavaScript verification tool.
    "JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
    – JSLint Documentation
    Use a simpler format to write innerscript
    Copy code The code is as follows:

    //Early code may look like this


    Copy the code The code is as follows:

    //The language attribute is not used now


    Always check data
    To check all data entered by your methods, on the one hand for security, On the other hand it is also for usability. Users enter incorrect data anytime and anywhere. It's not because they're stupid, it's because they're busy and think differently than you do. Use the typeof method to check whether the input your function accepts is legal.
    Copy code The code is as follows:

    //If the type of members is not an array, then the following The code will throw an error
    function buildMemberList(members){
    var all = members.length;
    var ul = document.createElement('ul');
    for(var i=0; i

    Copy code The code is as follows:

    //Good habits It is to check whether the parameter is an array
    function buildMemberList(members){
    //The typeof of the array is object, so if you want to determine whether it is an array, you can test whether it has a function that is only available for arrays: slice
    if(typeof members === 'object' &&
    typeof members.slice === 'function'){
    var all = members.length;
    var ul = document.createElement('ul' );
    for(var i=0;i

    Another security risk is to use data directly from the DOM. For example, your function gets the user name from the user name input box. Something but single or double quotes in the username may cause your code to crash
    Avoid global variables
    Global variables and global functions are very bad. All JavaScript contained in the page runs in the same domain, so if you declare global variables or global functions in your code, the variables and functions of the same name in the script files loaded in the subsequent code will be overwritten. Yours.
    Copy code The code is as follows:

    //Bad global variables and global functions
    var current = null;
    function init(){...}
    function change(){...}
    function verify(){...}

    There are many solutions. The method suggested by Christian Heilmann is:
    Copy the code The code is as follows:

    //If variables and functions do not need to be referenced "outside", then you can use an unnamed method to wrap them all.
    (function(){
    var current = null;
    function init(){...}
    function change(){...}
    function verify(){.. .}
    })();

    Copy code The code is as follows:

    //If variables and functions need to be referenced "outside", you need to put your variables and functions in a "namespace"
    //We use a function as a namespace here instead of a var, because declaring function in the former is simpler and can protect private data
    myNameSpace = function(){
    var current = null;
    function init(){...}
    function change (){...}
    function verify(){...}
    //All functions and attributes that need to be called outside the namespace must be written in return
    return{
    init :init,
    //You can even name an alias for functions and properties
    set:change
    }
    }();

    when declaring variables , always use var
    Variables in JavaScript may be global or local, and it will be more intuitive to declare them with var.
    Copy code The code is as follows:

    //Confusing problems caused by not using var in function
    var i=0; // This is good - creates a global variable
    function test() {
    for (i=0; i<10; i ) {
    alert("Hello World !");
    }
    }
    test();
    alert(i); // The global variable i is now 10!

    Copy the code The code is as follows:

    //The solution is to declare the variable in the function and also use var
    function test( ) {
    for (var i=0; i<10; i ) {
    alert("Hello World!");
    }
    }

    Use prefixes to convert strings into numbers
    In JavaScript, the " " operator is used to add numbers and concatenate strings. If you need to ask for the sum of several values ​​in a form, then using may cause problems.
    Copy code The code is as follows:

    //The code that will cause problems
    < form name="myform" action="[url]">



    function total() {
    var theform = document.forms["myform"];
    var total = theform. elements["val1"].value theform.elements["val2"].value;
    alert(total); // This will alert "12", but what you wanted was 3!
    }

    Copy code The code is as follows:

    //Add " in front of the string ”, which is a hint to JavaScript: this is a number, not a string
    function total() {
    var theform = document.forms["myform"];
    var total = ( theform. elements["val1"].value) ( ​​theform.elements["val2"].value);
    alert(total); // This will alert 3
    }

    Avoid using the eval() method
    The eval() method in JavaScript is a method to calculate/run any code as an object at runtime. In fact, due to security reasons, eval() should not be used in most cases. There is always a more "correct" way to accomplish the same job. The basic rule is, eval is evil, don't use it at any time unless you are a veteran and know you have to do it.
    for in statement
    When traversing all the items in an object, it is very convenient to use the for in statement. But sometimes we don't need to traverse the methods in the object. If not, we can add a filter.
    Copy code The code is as follows:

    //A for in statement with a filter added
    for(key in object) {
    if(object.hasOwnProperty(key) {
    ...then do something...
    }
    }

    Don't be lazy and omit "" and {}
    Technically, you can ignore a lot of curly braces and semicolons.
    Copy code The code is as follows:

    //Although it looks wrong, most browsers can parse this code correctly
    if(someVariableExists)
    x = false

    Copy code The code is as follows:

    //This code looks even more wrong. At first glance, it seems that the following sentences have been executed
    //In fact, only x=false is in if
    if(someVariableExists)
    x = false
    anotherFunctionCall();

    So, the principles to remember are: 1. Never omit a semicolon; 2. Do not omit curly braces unless they are on the same line middle.
    Copy code The code is as follows:

    //This is OK
    if(2 2 === 4) return 'nicely done';

    Use square brackets instead of periods when getting the properties of an object
    There are two ways to get the properties of an object in JavaScript:
    Copy code The code is as follows:

    //Dot mark
    MyObject.property

    Copy code The code is as follows:

    //square bracket mark
    MyObject["property"]

    If you use dot notation to obtain the properties of the object, the property name is hard-coded and cannot be changed at runtime; if you use square brackets, JavaScript will obtain the square brackets The inner value is then calculated to obtain the attribute name. In other words, using square brackets, the attribute name can be hard-coded, or it can be a variable or function return value.
    Copy code The code is as follows:

    //This won’t work
    MyObject.value i

    Copy code The code is as follows:

    //This way there is no Question
    MyObject["value" i]

    Assuming that JavaScript will be disabled
    I know that such an assumption will hurt the feelings of JavaScript developers, but in the current situation of unclear data We should make this assumption to be on the safe side. This is an important part of progressive enhancement.
    Use JavaScript libraries
    There are many very popular JavaScript libraries now, such as YUI, jQuery, and Dojo. Their disadvantage is that they need to download an additional file, but their advantages are more: greater compatibility; the code is simpler and easier to understand. There are many good libraries out there, but you shouldn't use them all in one project because there may be compatibility issues. Just choose one you are used to.
    Don’t forget that native JavaScript is undoubtedly faster. If it is used on a small scale, it is best to use native JavaScript.
    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn