24 Best Practices for JavaScript beginners

Source: Internet
Author: User
Tags script tag setinterval

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 which case the type of the operand will be cast to the same again for comparison, which may not be the result you want.

2.eval= Evil

Initially unfamiliar, "eval" allows us to access the JavaScript compiler (this looks very powerful). Essentially, we can pass the string to eval as a parameter and execute it.

This not only drastically reduces the performance of the script (the JIT compiler cannot predict the string content, but cannot precompile and optimize), and this also poses a huge security risk because it pays too much for the text to be executed.

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. Justifiably, this is a horrible practice that should be avoided at all costs. There is only one case where the curly braces can be omitted, but this is controversial.

if (2 + 2 = = 4) return ' nicely done ';

Rainy day

Most likely, one day you need to add more statements to the IF statement block. In that case, you have to rewrite this code. The bottom line--the omission is mined area.

4. Using JSLint

  JSLint is a debugger written by the famous Douglas (Douglas Crockford). Simply paste your code into the JSLint and it will quickly find the obvious problems and errors in the code.

"JSLint The source code of the sweep face input. If a problem is found, it returns a message that describes the problem and where the code is located. The problem is not necessarily a grammatical error, although this is usually the case. JSLint also looks at some coding styles and program structure issues. This does not guarantee that your program will be correct. It just provides another pair of eyes to help find the problem. The--jsling documentation

Before you deploy the script, run JSLint just to make sure you don't make any stupid mistakes.

5. Place the script at the bottom of the page

This technique has been mentioned in the previous articles in this series, and I am pasting the information here.

Remember-the first goal is to make the page as fast as possible to the user, the script folder is blocked, the script is loaded and executed, the browser can not continue to render the following content. 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-the horse's script is placed 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 computes the length of the array, and each time it iterates through the DOM query "container" element--the efficiency is serious underground!

Suggestions

var container = document.getElementById (' container ');

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 for everyone to share.

7. The best way to build a string

When you need to traverse 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 quickest way! Using native code, such as join (), is usually much faster than non-native, regardless of what is done inside the system. --james Padolsey, james.padolsey.com

8. Reducing global variables

As long as multiple global variables are organized under a single namespace, the likelihood of bad interaction with other applications, components, or libraries will be significantly reduced. --douglas Crockford

var name = ' Jeffrey ';

var = ' lastName ';

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 need to take a more reasonable name.

9. Add comments to the code

There seems to be no need, when please believe me, try to add more reasonable comments to your code. 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 summarize, 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 attracted by the idea that "most of my visitors have JavaScript enabled, so I don't have to worry." "However, this is a big misunderstanding.

Have you ever spent a moment looking at what your beautiful page looks like when JavaScript is turned off? (The Web Developer tool is easy to do (the translator notes: Chrome users download themselves in the App Store, ie users set up in Internet Options), which can make your site fragmented. As a rule of thumb, when designing your site, assume that JavaScript is disabled, and then, on that basis, gradually enhance your site.

11. Do not pass string arguments to "setinterval" or "setTimeout"

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 pass a string as a parameter to SetInterval and settimeout, but pass the function name as follows.

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;

}

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 members were very bad when they were set up." 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. Perhaps the traditional approach is to use the "new" constructor, like this:

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. Instead, I recommend that you use a more robust object literal method.

A better approach

var o = {

Name: ' Jeffrey ',

LastName = ' It ',

Somefunction:function () {

Console.log (this.name);

}

};

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." You do not need to call the constructor directly or 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 an object is needed, but to use an object when an array is needed." The rule is simple: You should use an array when the property name is a sequential integer. Otherwise, use the object "--douglas Crockford

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 suspect it's really accelerating here, but it can be clearer for your code.

17. Remember, do not omit semicolons

Technically speaking, 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 larger, harder-to-find problems.

A better approach

var Someitem = ' some string ';

function dosomething () {

return ' something ';

}

"For in" statement

When you traverse the properties of an object, you may find that the method function is also retrieved. To solve this problem, always wrap an If statement in your code 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. Use Firebug's "timer" function to optimize your code

Looking for a quick and easy way to determine how long the operation will take? Use Firebug's "timer" function to record 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!), there is nothing more appropriate than a book before lunch or go to bed, stick to a web development book on your bedside table. Here are some of my favorite JavaScript books.

    • object-oriented JavaScript (JavaScript Object-oriented Programming Guide PDF)
    • javascript:the Good Parts (JavaScript language Pristine revision PDF)
    • Learning JQuery 1.3 (jquery Basic Tutorial version 4th PDF)
    • 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 run automatically when the page loads or when the parent function is called. Simply wrap your function in parentheses and add an extra setting, essentially calling the 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 coding time, especially AJAX operations. As has been said, always remember that libraries can never be faster than native JavaScript code (assuming your code is correct).

The "Each" method of jquery is a great loop, but using native "for" statements is always faster.

23. The JSON of Douglas. Parse

Although JavaScript 2 (ES5) already has a JSON parser built in. But at the time of writing this article, we still need to implement it ourselves (compatibility). Douglas (Douglas Crockford), the father of JSON, has created a parser that you can use directly. Here you can download (the link is bad, you can view the relevant information here http://www.json.org/).

Simply import the script and you will get a new global JSON object that can then 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 (the Translator Note: HTML5 is obsolete, but if you like, you can still add it).

24 Best Practices for JavaScript beginners

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.