24 best practices for beginners of JavaScript (1)

Source: Internet
Author: User

1. Use = instead of =

JavaScript uses two different equivalent operators: = |! ==And ==|! =, It is the best practice to use the former in a comparison operation.

"If the operands on both sides have the same type and value, = true is returned ,! = False is returned ." -- JavaScript: the essence of language

However, when using = and! =, You may encounter different types. In this case, the type of the operand is forcibly converted to the same and then compared. This may not be the result you want.

2. Eval = evil

When we were not familiar with it at first, "eval" gave us access to the JavaScript compiler ). Essentially, we can pass a string to eval as a parameter and execute it.

This not only greatly reduces the performance of the script. Note: The JIT compiler cannot predict the content of the string, but cannot pre-compile and optimize it.) It also brings huge security risks, this is because the permission is too high for the text to be executed, so you can avoid it.

3. omitted may not save trouble

Technically, you can omit most curly braces and semicolons. Most browsers can correctly understand the following code:

 
 
  1. if(someVariableExists)  
  2.    x = false 

Then, if:

 
 
  1. if(someVariableExists)  
  2.    x = false  
  3.    anotherFunctionCall(); 

Some people may think that the above Code is equivalent to the following:

 
 
  1. if(someVariableExists) {  
  2.    x = false;  
  3.    anotherFunctionCall();  

Unfortunately, this understanding is incorrect. The actual meaning is as follows:

 
 
  1. if(someVariableExists) {  
  2.    x = false;  
  3. }  
  4. anotherFunctionCall(); 

You may have noticed that the indentation above is easy to give the illusion of curly braces. It is a terrible practice and should be avoided at all costs. In only one case, curly braces can be omitted when there is only one row, but this is controversial.

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

Preparations

It is very likely that you will need to add more statements in the if statement block one day. In this case, you must rewrite this code. Bottom line-omitted is the minefield.

4. Use JSLint

JSLint is a debugger written by the famous Douglas Crockford. Simply paste your code into the JSLint, which will quickly identify obvious problems and errors in the code.

"Source code entered by JSLint scanning. If a problem is found, it returns a message describing the problem and the location in the code. The problem is not necessarily a syntax error, though this is usually the case. JSLint will also view some encoding style and program structure problems. This does not guarantee that your program is correct. It just provides another pair of eyes to help identify problems ." -- JSLing document

Run JSLint before deploying the script, just to ensure that you have not made any stupid errors.

5. Place the script at the bottom of the page

This technique has been mentioned in previous articles in this series. I paste the information here.

Remember-the primary goal is to present the page to users as quickly as possible. The script is blocked. the browser cannot render the following content until the script is loaded and executed. Therefore, users are forced to wait for a longer period of time.

If your js is only used to enhance the effect-for example, click the button event-immediately place the script before the end of the body. This is definitely the best practice.

Suggestions

 
 
  1. <p>And now you know my favorite kinds of corn. </p>  
  2. <script type="text/javascript" src="path/to/file.js"></script>  
  3. <script type="text/javascript" src="path/to/anotherFile.js"></script>  
  4. </body>  

6. Avoid declaring variables in the For statement.

When executing lengthy for statements, make sure that the statement blocks are as concise as possible. for example:

Bad

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

Note that the length of the array should be calculated for each loop, and the dom query "iner" element should be traversed each time-the efficiency is very serious!

Suggestions

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

If you are interested, you can think about how to continue optimizing the above code. You are welcome to leave a comment to share with us.

7. optimal method for constructing strings

When you need to traverse arrays or objects, do not always think about the "for" statement. If you want to be creative, you can always find a better way, such as the following.

 
 
  1. var arr = ['item 1', 'item 2', 'item 3', ...];  
  2. var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>'; 

I'm not a god in your mind, but please believe that I don't believe you can test it yourself)-this is the fastest way to date! Using native code such as join () is usually much faster than non-native code, no matter what is done inside the system. -- James Padolsey, james.padolsey.com


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.