15 JavaScript Best Practices Summary _javascript Tips

Source: Internet
Author: User
This document collates most of the accepted, or less controversial, JavaScript good writing specifications (best Practice). Some of the obvious common sense is no longer discussed (for example, to use objects to support identifying judgments, rather than browsers to identify judgments; don't embed too deep). The order of entries is arranged roughly from high to low at an important level.
Place the external JavaScript file at the bottom of the HTML
Our goal is the same: to display content as quickly as possible for the user. When a script file is loaded, the HTML stops parsing until the script is loaded. As a result, the user may be facing a blank screen for a long time, and nothing seems to have happened. If your JavaScript code just adds features (such as button clicks), you'll see a noticeable increase in speed, even if you're bold enough to put the file references on the bottom of the HTML (just before </body>). If you are scripting files for other purposes, you need to consider them carefully. But in any case, this is certainly a very worthwhile place to consider.
Optimizing Loops
Loop through an array
Copy Code code as follows:

This bad code computes the length of an array every time it goes into the loop.
var names = [' George ', ' Ringo ', ' Paul ', ' John '];
for (Var i=0;i<names.length;i++) {
Dosomethingwith (Names[i]);
}

Copy Code code as follows:

In that case, it will only be counted once.
var names = [' George ', ' Ringo ', ' Paul ', ' John '];
var all = Names.length;
for (Var i=0;i<all;i++) {
Dosomethingwith (Names[i]);
}

Copy Code code as follows:

That's a little more brief.
var names = [' George ', ' Ringo ', ' Paul ', ' John '];
for (Var i=0,j=names.length;i<j;i++) {
Dosomethingwith (Names[i]);
}

Copy Code code as follows:

The bad thing about this code is that it puts the variable declaration inside the loop, and each loop creates a variable
for (var i = 0; i < somearray.length; i++) {
var container = document.getElementById (' container ');
container.innerhtml + = ' My number: ' + i;
Console.log (i);
}

Copy Code code as follows:

Declare a variable outside of the loop body, and the variable will only create 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
If you can increase readability, it makes sense to use the short format of the code, and here is an incomplete list:
Copy Code code as follows:

Only two times for conditional judgment, it's a lengthy writing.
var direction;
if (x > 100) {
Direction = 1;
} else {
Direction =-1;
}

Copy Code code as follows:

Better code
var direction = (x > 100)? 1:-1;

Copy Code code as follows:

To determine whether a variable is defined, if not, give a value, bad code
if (v) {
var x = V;
} else {
var x = 10;
}

Copy Code code as follows:

Better code
var x = v | | 10;

Copy Code code as follows:

Variable name repeated many times
var cow = new Object ();
Cow.colour = ' Brown ';
Cow.commonquestion = ' What now ';
Cow.moo = function () {
Console.log (' moo ');
}
Cow.feet = 4;
Cow.accordingtolarson = ' would take over the world ';

Copy Code code as follows:

The better way to do this is
var cow = {
Colour: ' Brown ',
Commonquestion: ' What now? ',
Moo:function () {
Console.log (' moo ');
},
Feet:4,
Accordingtolarson: ' would take over the world '
};

Copy Code code as follows:

Repeated a number of times group name
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 code 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 to use single quotes in JavaScript.
Copy Code code as follows:

Html


Copy Code code as follows:

Javascript
<script type= "Text/javascript" >
document.write (' <p> ');
</script>

Copy Code code as follows:

A piece of mixed jquery code
$ (' H1 '). After (' <div id= content ' >

avoid mixing with other technologies
CSS: Suppose our page has an input box (with class "mandatory") that must be filled in, and if it is not entered, a red border is added around it.
Copy Code code as follows:

A piece of code that mixes other technologies does this:
var f = document.getElementById (' mainform ');
var inputs = f.getelementsbytagname (' input ');
for (Var i=0,j=inputs.length;i<j;i++) {
if (Inputs[i].classname = = ' Mandatory ' &&
Inputs[i].value = = = ') {
Inputs[i].style.bordercolor = ' #f00 ';
Inputs[i].style.borderstyle = ' solid ';
Inputs[i].style.borderwidth = ' 1px ';
}
}

Copy Code code as follows:

A good piece of code would do this: give the stylized things to CSS.
var f = document.getElementById (' mainform ');
var inputs = f.getelementsbytagname (' input ');
for (Var i=0,j=inputs.length;i<j;i++) {
if (Inputs[i].classname = = ' Mandatory ' &&
Inputs[i].value = = = ') {
Inputs[i].classname + = ' ERROR ';
}
}

HTML: Assuming that we have more than one HTML content that needs to be loaded with JavaScript, using AJAX to load a separate file instead of using JavaScript to process the DOM can make the code difficult to handle, and there will be difficult to maintain compatibility issues.
validating JavaScript code
Browser processing JavaScript code can be very tolerant, but I recommend that you do not rely on the browser's parsing capabilities, so developed a lazy coding habits.
The easiest way to detect your code quality is through an online JavaScript validation tool, JSLint.
"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and a approximate location the source. The problem is isn't necessarily a syntax error, although it often is. JSLint looks at some style conventions as as a structural problems. It does not prove the your program is correct. It just provides another set of eyes to help spot problems. "
–jslint Documentation
Write innerscript using a simpler format
Copy Code code as follows:

The early code might be like this
<script type= "Text/javascript" language= "JavaScript" >
...
</script>

Copy Code code as follows:

Now you don't have to language the property.
<script type= "Text/javascript" >
...
</script>

always check data
To check all data entered by your method, on the one hand, for security, but also for usability. Users can enter the wrong data anytime, anywhere. This is not because they are stupid, but because they are busy and think differently. Use the TypeOf method to detect whether your function accepts input that is legitimate.
Copy Code code as follows:

If the members ' type is not an array, the following code throws an error
function Buildmemberlist (members) {
var all = Members.length;
var ul = document.createelement (' ul ');
for (Var i=0;i

Copy Code code as follows:

Good habit is to check whether the parameter is an array
function Buildmemberlist (members) {
The typeof of an array is object, so if you want to determine whether it is an array, you can test whether it has a function: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 take the data out of the DOM directly. For example, your function gets the user name from the User name input box, but the single or double quotes in the username may cause your code to crash.
Avoid global variables
Global variables and global functions are very bad. Because all of the JavaScript contained in a page runs in the same domain. So if you have a global variable or global function declared in your code, the same variable and function in the script file that is loaded in the following code will overwrite (overwrite) your.
Copy Code code as follows:

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

There are many solutions, Christian Heilmann suggested by:
Copy Code code as follows:

If variables and functions do not need to be "outside" references, then you can wrap them all up with a method that does not have a name.
(function () {
var current = null;
function init () {...}
function change () {...}
function verify () {...}
})();

Copy Code code 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 instead of a var because it is simpler to declare a function in the former and to protect the privacy data
MyNamespace = function () {
var current = null;
function init () {...}
function change () {...}
function verify () {...}
All functions and properties that need to be called outside the namespace are written in return.
return{
Init:init,
You can even name an alias for a function and a property
Set:change
}
}();

If you declare a variable, always use var
A variable in JavaScript may be a global domain or a local domain, which is more intuitive with the Var declaration.
Copy Code code as follows:

The problem of confusion caused by 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 Code code as follows:

The workaround is to declare the variable in the function, also with Var
function Test () {
for (var i=0; i<10; i++) {
Alert ("Hello world!");
}
}

Use the front + number to convert the string to a number
In JavaScript, the "+" operator is used as a numeric addition and is used to concatenate strings. If you need to find the number of values in the form, you may have problems with the + +.
Copy Code code as follows:

Code that will cause problems
<form name= "MyForm" action= "[url]" >
<input type= "text" name= "Val1" value= "1" >
<input type= "text" name= "Val2" value= "2" >
</form>
function Total () {
var theform = document.forms["MyForm"];
var total = theform.elements["Val1"].value + theform.elements["Val2"].value;
Alert (total); This'll alert "," but what you wanted was 3!
}

Copy Code code as follows:

Precede the string with "+", which is a hint to javascript: It's 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 would alert 3
}

Avoid using the eval () method
The eval () method in JavaScript is the method of calculating/running any code as an object at run time. In fact, because of security, most of the time should not use eval (), there is always a more "correct" way to do the same work. The basic principle is that the eval is evil, do not use it at any time unless you are a veteran and know that you have to.
For in statement
When iterating through all the entries in an object, it is convenient to use the for in statement. But sometimes we don't need to traverse the methods in the object, and if not, we can add a filter.
Copy Code code as follows:

Plus a filter for in statement
For (key in object) {
if (Object.hasownproperty (key) {
... then do something ...
}
}

Don't be lazy omit "and {}
Technically, you can ignore many curly braces and semicolons.
Copy Code code as follows:

Although it doesn't look right, most browsers can parse the code correctly.
if (somevariableexists)
x = False

Copy Code code as follows:

The code looks more wrong, and it seems that the following sentences have been executed.
In fact, only x=false in if
if (somevariableexists)
x = False
Anotherfunctioncall ();

So, the principle to remember is: 1. Never omit semicolons; 2. Do not omit curly braces unless they are in the same line.
Copy Code code as follows:

This is OK.
if (2 + 2 = = 4) Return to ' nicely done ';

To get an object property with square brackets instead of a point number
There are two ways to get properties of an object in javascript:
Copy Code code as follows:

Dot Sign
Myobject.property

Copy Code code as follows:

Square brackets Mark
Myobject["Property"]

If you use the dot mark to get the object's properties, the property name is hard-coded and cannot be changed at run time, and in square brackets, JavaScript obtains the value in square brackets and evaluates the property name by calculating the result. That is, the way the brackets are tagged, the property name can be hard-coded, or it can be a variable or a function return value.
Copy Code code as follows:

This is not going to work.
Myobject.value+i

Copy Code code as follows:

So there's no problem.
myobject["value" +i]

Suppose JavaScript is disabled
I know this assumption will hurt the JavaScript developer's feelings, but we should make this assumption for security purposes in the current uncertain data. This is a very important part of progressive enhancement.
using JavaScript libraries
Now there are a lot of very popular JavaScript libraries, such as Yui and jquery, Dojo. Their disadvantage is that they need to download an additional file, with more advantages: more compatibility, more straightforward code. There are a lot of good libraries, but you shouldn't use them in a project because there may be compatibility issues. Choose a habit of your own is good.
The point to remember is that native JavaScript is no doubt faster, and if it's a small use, it's best to use native.

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.