24 best practices for beginners of JavaScript

Source: Internet
Author: User

Original article: 24 JavaScript Best Practices for Beginners

(Note: When I read the original article, I did not pay attention to the release date. If I think it is good, I will translate itJSON.parseIn that section, I found that it was an article published in 2009, but it was still good. In addition, although there are only 23 best practices in the article, I don't know how the original author missed one .)

1. Priority =, rather than =

JavaScript uses two equality operators:===,!==And==,!=. It is generally considered that the best practice for comparison is to use the previous operator group.

"If the two operands have the same type and value===The comparison result is true,!==The comparison result is false. "--- JavaScript (JavaScript: The Good Parts)

However, if you use==And!=When comparing different types of operands, you will encounter problems. In this case, this set of operators will try to perform useless forced conversion on the value of the operand.

2. Eval is synonymous with bad

For those who are not familiar with JavaScript, the function "evel" allows us to access the JavaScript compiler. We can pass a string parameter to "eval" to obtain the string execution result.

This not only greatly reduces the performance of your script, but also creates a huge security risk, because it gives too much ability to pass in plain text. Avoid using eval functions as much as possible.

3. Do not be lazy

Technically, you may be lucky to omit most curly braces and semicolons. Most browsers correctly interpret the following code snippets:

if(someVariableExists)    x = false

However, consider the code below:

if(someVariableExists)    x = false    anotherFunctionCall();

Some people may think that the previous code is equivalent:

if(someVariableExists) {    x = false;    anotherFunctionCall();}

Unfortunately, he is wrong. In fact, its intention is:

if(someVariableExists)    x = false;anotherFunctionCall();

You should have noticed that the indentation in the Code imitates the curly brackets function. Undoubtedly, this is a terrible practice and should be avoided in any case. The only statement that can omit curly braces is in a row. However, this case is controversial.

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

Always think about future

What if you need to add more commands in such an if statement at a later time? You can only rewrite this code. The bottom line for handling this problem is to exercise caution when writing an omitted statement.

4. Use JS Lint

JSLint is a debugger written by Douglas Crockford. Simply copy your script, it will quickly scan your code for any obvious problems and errors.

>

"JSLint obtains a JavaScript source code and then scans the code. If a problem is found, a message is returned to describe the problem and the approximate location of the problem in the source code. Although the problem is often caused by syntax errors, it is not necessarily true. JSLint will also check some style habits and structure issues. It does not prove that your code is correct, but provides another pair of eyes to help you find problems. "--- JSLint documentation

Before writing the script code, execute JSLint once to ensure that you do not make stupid mistakes.

5. Place the script at the bottom of the page

This technique was also recommended in previous articles in this series. Because it is also very suitable here (As it's highly appropriate though), I paste that information directly here.

Remember-the main goal of this best practice is to load pages for users as quickly as possible. When a script is loaded, the browser cannot continue until the entire script file is fully loaded. Therefore, the user must wait for a longer time to notice any progress.

If the purpose of a JS file is only to add features-for example, after clicking a button-Put those files at the bottom and before the body ends the tag. This is definitely a best practice.

Better Practices

And now you know my favorite kinds of corn.

<script type="text/javascript" src="path/to/file.js"></script><script type="text/javascript" src="path/to/anotherFile.js"></script>
6. Declare variables outside of the For statement

When a lengthy "for" statement is executed, let the interpretation engine do the necessary work. For example:

Bad practices

for(var i = 0; i < someArray.length; i++) {    var container = document.getElementById('container');    container.innerHtml += 'my number: ' + i;    console.log(i);}

Note that the length of the array needs to be checked for each iteration in the code snippet above, and the DOM tree needs to be traversed each time to find the "container" element-How inefficient it is!

Better Practices

var container = document.getElementById('container');for(var i = 0, len = someArray.length; i < len; i++) {    container.innerHtml += 'my number: ' + i;    console.log(i);}

I would like to thank a friend for leaving a comment to demonstrate how to further optimize the code block above.

7. The fastest way to build strings

When you need to traverse an array or object, do not always use the "for" statement that you can stick. Creatively find the fastest solution to complete the work.

var arr = ['item 1', 'item 2', 'item 3', ...];var list = '
  
  
  • ' + arr.join('
  • ') + '
';

>

"I won't bother you with the benchmark. You just have to trust me (or test it yourself)-this is the fastest way so far! "

The use of native methods (such as join () is usually much faster than any non-native method, regardless of what happens behind the abstraction layer. --- James Padolsey, james.padolsey.com"

8. Reduce global variables

>

"By encapsulating global things into a single namespace, it can greatly reduce the probability of chaotic interaction with other applications, components, and code libraries. "--- Douglas Crockford

var name = 'jeffrey';var lastname = 'Way';function doSomething() {...}console.log(name);      // Jeffrey -- or window.name

Better Practices

var DudeNameSpace = {    name: 'Jeffrey',    lastname: 'Way',    doSometing: function() {...}}console.log(DudeNameSpace.name);    // Jeffrey

Note how we can reduce the global "footprint" to a "DudeNameSpace" object named as a joke.

9. Comment out your code

It seems unnecessary at first, but believe me, you will want to comment your code as well as possible. What happens when you return to the project in a few months? You can't easily remember what you thought about each line of code. Or what if one of your colleagues needs to modify your code? Always remember to comment out the important part of your code.

// Cycle through array and echo out each namefor(var i = 0, len = array.length; i < len; i++) {    console.log(array[i]);}
10. embracing progressive enhancement

Always consider how to handle JavaScript disabling. Maybe you will think, "most of my web page readers use JavaScript, so I am not worried about this problem ." However, this is a huge mistake.

Did you take the time to see what your beautiful slide looks like when JavaScript is disabled? (Download the Web Developer toolbar to facilitate this operation .) Maybe it will completely damage your site. Based on past experience, you should assume that JavaScript will be disabled when designing your site. Then, once you do this, gradually enhance your webpage layout!

11. Do not pass the string to "SetInterval" or "SetTimeOut"

Consider the following code:

setInterval("document.getElementById('container').innerHTML += 'my new number: ' + i", 3000);

This code is not only inefficient, but also acts the same way as the "eval" function. Never pass the string to SetInterval or SetTimeOut. Instead, a function name should be passed.

setInterval(someFunction, 3000);
12. Do not use the "With" Statement

At first glance, the "With" statement seems to be a clever idea. The basic concept is that they provide a shorthand for accessing deep nested objects. For example...

with (being.person.man.bodyparts) {    arms = true;    legs = true;}

Replace the following statement

being.person.man.bodyparts.arms = true;being.person.man.bodyparts.legs = true;

Unfortunately, after some tests, we will find that the short form performs very poorly when setting new members. As an alternative, you should use var.

var o = being.person.man.bodyparts;o.arms = true;o.legs = true;
13. Use {} instead of New Object ()

JavaScript supports multiple object creation methods. Perhaps the more traditional method is to use the "new" constructor, like this:

var o = new Object();o.name = 'Jeffrey';o.lastname = 'Way';o.someFuncion = function() {    console.log(this.name);}

However, this method is considered "bad practice" because its behavior is not what we think. Instead, I recommend you use a more robust object literal method.

Better Writing

var o = {    name: 'Jeffrey',    lastName: 'Way',    someFunction: function() {        console.log(this.name);    }};

Note: If you just want to create an empty object, {} will be used.

var o = {};

>

"The literal volume of objects enables us to write code that supports many features, and the code is still relatively intuitive to the implementers of the Code. You do not need to directly call the constructor or maintain the correct sequence of parameters passed to the function. "--- Dyn-web.com

14. Use [] instead of New Array ()

This applies to creating a new array.

Decent Writing Method

var a = new Array();a[0] = 'Joe';a[1] = 'Plumber';

Better Writing

var a = ['Joe', 'Plumber'];

>

"A common error in JavaScript is that an array is used when an array is required or when an object is required. The rule is simple: when the attribute name is a small continuous integer, you should use an array. Otherwise, use the object "--- Douglas Crockford

15. A long string of variables? Omit the "var" keyword and use commas instead.
var someItem = 'some string';var anotherItem = 'another string';var oneMoreItem = 'one more string';

Better Writing

var someItem = 'some string',    anotherItem = 'another string',    oneMoreItem = 'one more string';

It is quite self-evident. I don't know if there is any real speed improvement here, but it makes your code more concise.

16. Always, always use a semicolon

Technically, most browsers allow you to omit semicolons.

var someItem = 'some string'function doSomething() {    return 'something'}

Even so, this is a very bad practice, which may lead to more problems and make it more difficult to find problems.

Better Writing

var someItem = 'some string';function doSomething() {    return 'something';}
18. "For in" Statement

When traversing members in an object, you will also get method functions. To solve this problem, you should always wrap your code in an if statement to filter information.

for(key in object) {    if(object.hasOwnProperty(key)) {        ... then do something...    }}

ReferenceJavaScript: the essence of language, written by Douglas Crockford

19. Use the "Timer" feature of Firebug to optimize code

Does it take a quick and easy way to detect how long an operation takes? Use the "timer" feature of Firebug to record the results.

function TimeTracker() {    console.time("MyTimer");    for(x=5000; x > 0; x--){}    console.timeEnd("MyTimer");}
20. Read, read, and read again

I am a super fan of a Web development blog (such as this blog !), However, for lunch or bedtime, blogs are not a substitute for books. Always put a wen development book in front of your bed. The following are some of my favorite JavaScript books.

Object-oriented JavaScriptJavaScript: A crazy Ajax handout JavaScript Learning Guide

Read more times. I am still reading!

21. Self-Executing Functions)

Compared with calling a function, it is easier to automatically execute a function when the page loads or calls the parent function. Simply wrap your function in parentheses and add an additional pair of parentheses. In essence, this function is called.

(function doSomething() {    return {        name: 'jeff',        lastName: 'way'    }; })();
22. The original (raw) JavaScript code is always executed faster than the code library.

JavaScript code libraries, such as jQuery and Mootools, can save you a lot of coding time-especially when using AJAX. Even so, keep in mind that the execution speed of the code base is always inferior to that of the original JavaScript code (assuming that the code is correct ).

JQuery's "each" method is very good for traversing, but the use of native "for" statements will always be faster.

23. Crockford's JSON. Parse

Although JavaScript 2 should have a built-in JSON parser, we still need to implement it ourselves when writing this article. Douglas Crockford, the creator of JSON, has implemented a parser for you to use. You can download it from here.

Simply import the script to obtain a new JSON Global Object for parsing 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 += '
  • ' + response[i].name + ' : ' + response[i].email + '
  • ';}
    24. Delete "Language"

    A few years ago, the "language" attribute was common in the script tag.

    <script type="text/javascript" language="javascript">...</script>

    However, this attribute has been abandoned for a long time, so you should stop using it.

    That's all, comrades.

    Now you know the 24 basic skills that JavaScript Beginners should know. If you have the opportunity, let me know your tips. Thank you for reading.

    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.