Use JSLint to refine JavaScript code

Source: Internet
Author: User

JavaScript is becoming increasingly popular due to the prevalence of mobile applications and the widespread use of HTML5. JavaScript is popular in part because it is flexible and convenient, and you can get started quickly. It does not require heavyweight development environments or third-party application support, as long as you open a text editor, save and run it in a web browser.

However, for beginners, There are traps everywhere when using JavaScript. In a complex script, the scalability of JavaScript often causes weird bugs. For example, undeclared local variables may unconsciously modify global variables.

Now, open the JSLint website. As its website says, it is a "JavaScript code quality tool ". The author of JSLint is Douglas Crockford, which is famous for its contributions to JavaScriptECMAScript and JSON.

Annotation: Douglas Crockford is one of The technical authorities in The web field. He is The creator of JSON, JSLint, JSMin, and ADSafe, and is also a famous Chinese version of JavaScript: The Good Parts, The essence of JavaScript language.). I have written many widely-spread and influential technical articles, including "JavaScript: the most misunderstood language in the world ".)

JSLint helps JavaScript programmers follow certain coding specifications during programming. JSLint is based on Strict Mode), refer to version 5th ECMAScript standard. In strict mode, your code needs to run according to more strict rules than in normal mode.

For more information about Strict Mode, see the two articles "Introduction to ECMAScript 5.1": how to use Strict Mode to improve team development efficiency ".

Use JSLint

Let's use JSLint to run an example. Write a simple jQuery plug-in to display the information received by msg through the prefix. If the value passed to the type is false, the prefix is not displayed.

 
 
  1. (function ($) {  
  2.     $.fn.loading = function(msg, type, cssClass){  
  3.         var prefixes = {  
  4.             warning: 'Warning: ' + msg,  
  5.             error: 'Error: ' + msg,  
  6.             info: 'Info: ' + msg,  
  7.             warning: 'Caution: ' + msg,  
  8.         };  
  9.         if (type) {  
  10.             concatMsg = prefixes[type];  
  11.         } else {  
  12.             concatMsg = msg;  
  13.         }  
  14.         $(this).each(function()  {  
  15.             var tis = $(this)  
  16.             if (msg == false) {  
  17.                 tis.html('');  
  18.             } else {  
  19.                 tis.html(concatMsg);  
  20.             }  
  21.         });  
  22.      }  
  23. })(jQuery); 

Although this code runs normally as a jQuery plug-in, when you use Firefox or Chrome to run it, you will find several obvious errors and some imperceptible problems. Instead of solving these problems with mental power, it is better to use JSLint to help us. Copy the above Code to the text box of the JSLint website, and click the "JSLint" button. The Code suggestions and error prompts will appear below.

The first error in JSLint is the loss of the "use strict" statement. This error indicates that the function is not executed in strict mode. To correct this error, we add the "use strict" statement in the header of the function body to start the strict mode.

 
 
  1. 'use strict'; 

After the strict mode declaration statement is added, click the "JSLint" button again, and the error message indicating the loss of "use strict" will disappear. Now, we can continue to see the next error. The following error is about space. We can ignore it with confidence because it cannot be regarded as a real error.

You can change the "messy white space" option at the bottom of the page to "true", so that you can retain the function keyword without spaces. But now, we keep the default attribute of the "messy white space" option, because this feature will also help us check other space problems, so let's talk about it later.

It is also worth noting that although the second and third errors pointed out by JSLint point to the same line of code, the error points are not the same. In the latter JSLint, we recommend that you set a blank space between the right brace ")" and the left brace "{". Now we can correct this error.

Insert a space and click the "JSLint" button again. The next error is displayed in line 1 and contains 8th characters. The prefixes object contains two identical warning attributes and modifies the second warning to caution.

This time, I will not click the "JSLint" button. Let's look at the next error. A comma is added at the end of the code block that defines the object. For errors like this, Chrome and Firefox may be ignored, but IE will not be so friendly, so we will remove this comma.

The subsequent two errors point to the undefined variable concatMsg. If a variable is not defined in the current scope, JavaScript searches globally to see if it has been defined elsewhere. If you introduce external code and define the variable globally, you may need to break your head and find out the cause of the bug. Fortunately, with JSLint, we can put such errors in the cradle.

Correct the error and refactor the code. Because the default value of concatMsg is msg, we can assign msg to it first and then modify it as needed. The code for concatMsg is as follows:

 
 
  1. var concatMsg = msg;  
  2. if (type) {  
  3.     concatMsg = prefixes[type];  

To continue, there is a space problem similar to the previous one. correct it. Then, JSLint indicates that a semicolon is missing, as shown in ). JSLint assumes that the command line without the end of a semicolon will never be terminated. Therefore, if appears below, JSLint considers that there should be a semicolon. Although the ending Semicolon is dispensable according to the language specification, it is a good habit to add it. This type of bad code can easily cause inexplicable bugs in large project collaboration. Therefore, this type of problem should be avoided during normal coding.

Next is a good example of errors. In JavaScript, there is a comparison between 'Equality '=) and strict 'Equality' =. In this case code, if strict 'Equality 'is not used, the if value is true regardless of whether msg is a null string or false. Therefore, we use strict 'Equality 'for comparison.

Okay. Let's click "JSLint" again. As shown in, the error occurs in row 10th, and JSLint considers the merging variable Declaration as a good coding standard. Although the concatMsg variable declaration follows prefixes, JSLint considers that it is better to complete the variable declaration in a command statement by comma.

The next error is about the format. At first glance, it's not just a matter of time. However, in a large number of scripts, this indentation problem may cause hard-to-find bugs. Therefore, to ensure code uniformity, we should move forward to a grid.

The next problem is similar to the previous one, but the form is different. JavaScript Functions can also belong to variables, so like other variable assignment statements, JSLint wants to add a semicolon at the end.

Finally, as shown below, there are two errors in the last line. The first problem is that JSLint suggests moving the closed brackets after jQuery, because this will not cause ambiguity in the closure function definition. Second, JSLint considers that the jQuery variable does not exist. But in fact, you may have introduced the jQuery file in the actual page, so we can enter "jQuery" in the text box at the bottom of the page to solve this problem: JSLint Directive text box ).

Run JSLint again, And it prompts that the function needs to receive three parameters. However, in this example, we have never used the third parameter. Therefore, there are two ways to solve this problem. First, delete the third parameter. Second, change the "unused parameters" item below to true. If you need to retain this parameter for some reason, use the second method.

The improved code with JSLint is as follows:

 
 
  1. (function ($) {  
  2.     'use strict';  
  3.     $.fn.loading = function (msg, type, cssClass) {  
  4.         var prefixes = {  
  5.             warning: 'Warning: ' + msg,  
  6.             error: 'Error: ' + msg,  
  7.             info: 'Info: ' + msg,  
  8.             caution: 'Caution: ' + msg  
  9.         }, concatMsg = msg;  
  10.         if (type) {  
  11.             concatMsg = prefixes[type];  
  12.         }  
  13.         $(this).each(function () {  
  14.             var tis = $(this);  
  15.             if (msg === false) {  
  16.                 tis.html('');  
  17.             } else {  
  18.                 tis.html(concatMsg);  
  19.             }  
  20.         });  
  21.     };  
  22. }(jQuery)); 

JSLintCommand

You can use the JSLint command to directly define the JSLint variable in your source code. In this way, you do not need to perform back-and-forth operations on the page. The following example defines jQuery global variables and sets "unparam" to true.

 
 
  1. /*global jQuery*/ 
  2. /*jslint unparam: true */ 
  3. (function ($) {  
  4.     ‘use strict’;  
  5. …  
  6. }(jQuery)); 

Summary 

In this short example, JSLint points out some obvious and easily overlooked errors. Before running the code, using JSLint to help us find some errors can effectively improve our development efficiency and code quality. If you really want to write high-quality code, check it with JSLint before running it on the server. JSLint also provides an independent JS file version, so you can download it and run it online and offline!

---------------- I am a split line ---------------

Translator:

Strict mode is not supported by all browsers. This is a browser-supported statistical table. The front-end of a Web page may not follow the strict mode for a long time, but it is better to use the strict mode in mobile development. Whether or not they can be used at present, I think front-end engineers should use these tools to help themselves develop good coding habits. Good habits will benefit you a lot, here is a slightly exaggerated reference of a sentence in the movie Iron Maiden: Watch your habits, for they become your character

Using JSLint to Refine Your Code

Http://blog.jobbole.com/29583/.

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.