24 Best Practices for JavaScript beginners

Source: Internet
Author: User
Tags deprecated script tag

24 Best Practices for JavaScript beginners

1. Use = = = instead of = =
JavaScript uses 2 different equivalent operators: ===|! = = and ==|! =, it is best practice to use the former in the comparison operation.

"If the operands on both sides have the same type and value, = = = Returns true,!== returns FALSE." "--javascript: the Essence of language
However, when using = = and! = When you may encounter different types of situations,
In this case, the type of the operand is cast to the same and then compared,
This may not be the result you want.
2.eval= Evil
Initially unfamiliar, "eval" allows us to access JavaScript's compilation
(this looks very powerful). Essentially, we can put the string
Passed to Eval as an argument, and executes it.
This not only drastically reduces the performance of the script: the JIT compiler cannot predict the string
Not pre-compiled and optimized), and this can also lead to huge security
Because it pays too much for the text to be executed.
Code Farm 27
3. Omission may not be convenient
Technically speaking, you can omit most curly braces and semicolons. Most browsers
Can correctly understand the following code:
if (somevariableexists)
x = False
Then, if it looks like this:
if (somevariableexists)
x = False
Anotherfunctioncall ();
One might think that the above code is equivalent to the following:
if (somevariableexists) {
x = false;
Anotherfunctioncall ();
}
Unfortunately, this understanding is wrong. The actual meaning is as follows:
if (somevariableexists) {
x = false;
}
Anotherfunctioncall ();
You may have noticed that the indentation above is easy to give the illusion of curly braces. Non-available
This is a horrible practice that should be avoided at all costs. There is only one situation
When there is only one row, the curly braces can be omitted, but this is a full
Controversial.
if (2 + 2 = = 4) return ' nicely done ';
Code Farm 28
Rainy day
Most likely, one day you need to add more statements to the IF statement block. Such a
, you must rewrite this code. The bottom line--the omission is mined area.
4. Using JSLint
JSLint was written by the famous Douglas (Douglas Crockford)
The debugger. Simply paste your code into the JSLint and it will quickly find
Obvious problems and errors in the code.
"JSLint The source code of the sweep face input. If a problem is found, it returns a description of the problem and
A message in the same location in the code. The problem is not necessarily a grammatical error, although it is usually
Sample. JSLint also looks at some coding styles and program structure issues. This does not guarantee that your journey will be
The order is correct. It just provides another pair of eyes to help find the problem. ”
--jsling Documentation
Before deploying the script, run JSLint just to make sure you don't make any foolish
Stupid mistake.
5. Place the script at the bottom of the page
This technique has been mentioned in the previous articles in this series, and I pasted the information in
Over here.
Code Farm 29
Remember-the primary goal is to make the page as fast as possible to the user, the script folder
Before the script is loaded and executed, the browser cannot continue rendering the
The contents of the polygon. As a result, users will be forced to wait longer.
If your JS is only used to enhance the effect--for example, a button's Click event--
Put the script immediately before the body ends. This is definitely the best practice.
Suggestions
<p>and now know my favorite kinds of corn. </p>
<script type= "Text/javascript" src= "Path/to/file.js" ></
Script>
<script type= "Text/javascript" src= "path/to/anotherfile.
JS "></script>
</body>
6. Avoid declaring variables within a for statement
When executing a lengthy for statement, keep the statement block as concise as possible, for example:
Bad
for (var i = 0; i < somearray.length; i++) {
var container = document.getElementById (' container ');
container.innerhtml + = ' My number: ' + i;
Console.log (i);
}
Note that each loop calculates the length of the array and iterates through the DOM each time
Query "container" element--serious underground!
Suggestions
var container = document.getElementById (' container ');
Code Farm 30
for (var i = 0, len = somearray.length; i < Len; i++) {
container.innerhtml + = ' My number: ' + i;
Console.log (i);
}
Interested can think about how to continue to optimize the above code, welcome to leave a comment on everyone
Share.
7. The best way to build a string
When you need to iterate over an array or object, don't always think about the "for" statement,
Be creative and always find a better way, for example, like this.
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...];
var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></
Ul> ';
I am not God in your heart, but please believe me (do not believe in your own test)--this is by far the most
Quick Way! Using native code (such as Join ()), regardless of what is done inside the system, is usually more than the non-
Native is much faster.
--james Padolsey, james.padolsey.com
8. Reducing global Variables
As long as multiple global variables are organized under a single namespace, it will be significantly reduced with other applications
The likelihood of a bad interaction between a program, component, or class library.
--douglas Crockford
var name = ' Jeffrey ';
var = ' lastName ';
Code Farm 31
function dosomething () {...}
Console.log (name); Jeffrey--or Window.name
A better approach
var dudenamespace = {
Name: ' Jeffrey ',
LastName: ' The ' to ',
Dosomething:function () {...}
}
Console.log (Dudenamespace.name); Jeffrey
Note: Here is simply named "Dudenamespace", the actual
Take a more reasonable name.
9. Add comments to the code
There seems to be no need, when please believe me, try to add a more reasonable note to your code
Release. When you look at your project after a few months, you may not remember your idea.
Or, what if one of your coworkers needs to change your code? To sum up, give
Adding comments to your code is an important part.
Loop array, output each name (Translator Note: This kind of comment seems a bit superfluous).
for (var i = 0, len = array.length; i < Len; i++) {
Console.log (Array[i]);
}
10. Embrace progressive enhancement
Ensure that JavaScript is disabled and can be degraded smoothly. We are always so
The idea attracts, "most of my visitors have JavaScript enabled, so I
Don't worry. "However, this is a big misunderstanding.
Code Farm 32
Have you ever spent a moment looking at your beautiful page when JavaScript is turned off
What's it like? (Downloading Web Developer tools makes it easy to do
To (Translator Note: Chrome users download themselves in the App Store, ie users
Internet options), which could make your site fragmented. As
A rule of thumb, when designing your site, assume that JavaScript is disabled,
Then, on this basis, gradually enhance your website.
11. Do not give "setinterval" or "SetTimeout "Passing String Parameters
Consider the following code:
SetInterval (
"document.getElementById (' container '). InnerHTML + = ' My
New number: ' + i ', 3000
);
Not only inefficient, but this approach is the same as "eval". Never give
SetInterval and SetTimeout pass strings as arguments, but like the following
This passes the function name.
SetInterval (SomeFunction, 3000);
12. Do not use the "with" statement
At first glance, the "with" statement looks like a smart idea. The basic idea is that
It can provide abbreviations for accessing deep nested objects, such as ...
With (Being.person.man.bodyparts) {
Arms = true;
Legs = true;
Code Farm 33
}
And not like this:
Being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;
Unfortunately, after testing, it was found that "the new member was set up very
Bad. Instead, you should use variables like the following.
var o = being.person.man.bodyparts;
O.arms = true;
O.legs = true;
13. Use {} instead of new Ojbect ()
There are several ways to create objects in JavaScript. It's probably the traditional way.
Use the "new" constructor, as follows:
var o = new Object ();
O.name = ' Jeffrey ';
O.lastname = ' the ' ";
O.somefunction = function () {
Console.log (this.name);
}
However, this approach has been criticized less than in practice. As a substitute, I built
You use a more robust object literal method.
A better approach
var o = {
Name: ' Jeffrey ',
LastName = ' It ',
Somefunction:function () {
Console.log (this.name);
Code Farm 34
}
};
Note that if you just want to create an empty object, {} is better.
var o = {};
"The object literal allows us to write more distinctive code, and it's relatively simple." No need
To call the constructor directly or to maintain the correct order of the arguments passed to the function, etc. "
--dyn-web.com
14. Use [] instead of the new Array ()
The same applies to creating a new array.
For example:
var a = new Array ();
A[0] = "Joe";
A[1] = ' Plumber ';
A better approach:
var a = [' Joe ', ' Plumber '];
"The common mistake in a JavaScript program is to use an array when the object is needed, while the number
Group, the object is used. The rule is simple: when the property name is a sequential integer, you should make the
With an array. Otherwise, use the object "
--douglas Crockford
Code Farm 35
15. When defining multiple variables, omit the var keyword and replace it with a comma
var Someitem = ' some string ';
var Anotheritem = ' another string ';
var onemoreitem = ' One more string ';
A better approach
var Someitem = ' Some string ',
Anotheritem = ' Another string ',
Onemoreitem = ' one more string ';
... It should be self-evident. I doubt it's really accelerating here, but it could be your generation.
The code is clearer.
17. Remember, do not omit semicolons technically, most browsers allow you to omit semicolons.
var Someitem = ' Some string '
function dosomething () {
Return ' something '
}
It has been said that this is a very bad practice that could lead to greater, difficult
The problem found.
A better approach
var Someitem = ' some string ';
function dosomething () {
Code Farm 36
return ' something ';
}
"for in" statement
When you traverse the properties of an object, you may find that the method function is also retrieved. In order to
To solve this problem, always wrap your code in an if statement to filter the information.
For (key in object) {
if (Object.hasownproperty (key) {
... then do something ...
}
}
Reference JavaScript: The essence of Language, Douglas (Douglas Crockford).
19. Using Firebug's "timer" function to optimize your code is looking for a quick and easy way to determine how long it takes to operate? MakeUse the Firebug "timer" function to record the results.
function Timetracker () {
Console.time ("MyTimer");
for (x=5000; x > 0; x--) {}
Console.timeend ("MyTimer");
}
20. Read, read, read repeatedly
Although I am a fan of a huge web development blog (like this!), the lunch
Or go to bed before, there is really nothing more appropriate than a book, insist on putting
Code Farm 37
A web development book on your bedside table. Here are some of my favorite
JavaScript Books.
Y object-oriented JavaScript (JavaScript Object-oriented Programming Guide PDF)
Y javascript:the Good Parts (JavaScript language Pristine revision pdf)
Y Learning jquery 1.3 (jquery Basic Tutorial 4th edition pdf)
Y learning JavaScript (JavaScript learning guide pdf)
Read them ... Times. I will still continue!
21. Self-executing functions
Similar to calling a function, it is simple to make a function in a page load or a parent
Run automatically when the function is called. Simply wrap your function in parentheses.
Then add an extra setting, which is essentially called a function.
(function dosomething () {
return {
Name: ' Jeff ',
LastName: ' The ' to '
};
})();
22. Native code is always faster than library
JavaScript libraries, such as jquery and MooTools, can save a lot of
Encoding time, especially AJAX operations. Have said, always remember that the library always
Can't be faster than native JavaScript code (assuming your code is correct).
The "Each" method of JQuery is a great loop, but uses native "for" statements
Always faster.
Code Farm 38
23. The JSON of Douglas. Parse
Although JavaScript 2 (ES5) already has a JSON parser built in. But in
When writing this article, we still need to implement it ourselves (compatibility). Douglas
(Douglas Crockford), the father of JSON, has created a you can
The parser that is used directly. Here can download (link is bad, can be found here
See related information http://www.json.org/).
Simply import the script, you will get a new global JSON object, and then
Can be used to parse your JSON file.
var response = Json.parse (Xhr.responsetext);
var container = document.getElementById (' container ');
for (var i = 0, len = response.length; i < Len; i++) {
container.innerhtml + = ' <li> ' + response[i].name + ':
' + response[i].email + ' </li> ';
}
24. Remove the "language" attribute
The "language" attribute in the script tag was very common.
<script type= "Text/javascript" language= "JavaScript" >
...
</script>
However, this attribute has already been deprecated, so please remove it (Translator Note: HTML5
Deprecated, but if you like, you can still add).

Transferred from the 12-year-code farm

24 Best Practices for JavaScript beginners

Related Article

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.