Key points for writing high-quality JavaScript code (1)

Source: Internet
Author: User

This abstract also includes some habits that are not relevant to the code, but is closely related to the creation of the overall code, including writing API documents, performing peer reviews, and running JSLint. These habits and best practices can help you write better, easier to understand, and maintain code that will be proud to look back in a few months or years.

Writing Maintainable Code)

Fixing software bugs is expensive, and the cost of these bugs increases over time, especially when these bugs lurks and gradually appear in released software. It is best to fix a bug immediately when you discover it. At this time, the problem that your code will solve is very clear in your mind. Otherwise, you move to another task and forget the specific code. You need to view the code after a while:

◆ Spend time learning and understanding this question

◆ Time is the code for understanding the issues to be solved

There are still problems, especially for large projects or companies, the guy who fixes the bug is not the one who writes the Code (and found that the bug is not the same person who fixes the bug ). Therefore, it is necessary to reduce the time required to understand the code generation, whether it is code written by yourself some time ago or code written by other members of the team. This is related to the bottom line (business revenue) and the happiness of developers, because we should develop new exciting things instead of spending hours and days to maintain legacy code.

Another fact related to software development life is that it takes much time to read code than to write code. Sometimes, when you focus on and think deeply about a problem, you can sit down and write a lot of code one afternoon.

Your code can work very quickly, but as the application matures, there will be many other things happening, which requires you to review, modify, and adjust. For example:

◆ The bug is exposed.

◆ New features are added to applications

◆ Programs work in a new environment (for example, new browsers appear on the market)

◆ Code change Purpose

◆ The code should be completely re-written from the beginning, transplanted to another architecture, or even in another language

As a result of these changes, the code that is rarely written by several hours has finally evolved into reading the code for weeks. This is why creating maintainable code is crucial to the success of the application.

The maintained code means:

◆ Readable

◆ Consistent

◆ Predictable

◆ It Looks Like written by the same person

◆ Recorded

Minimizing Globals)

JavaScript manages scopes through functions. The variables declared within the function are only within the function, and the function is unavailable outside. On the other hand, global variables are declared or not declared outside any function for simple use.

Each JavaScript environment has a global object that can be accessed when you use this outside any function. All the variables you create become the attributes of the global object. In the browser, for convenience, this global object has an additional attribute called window, which usually points to the global object itself. The following code snippet shows how to create and access global variables in the browser environment:

 
 
  1. Myglobal = "hello"; // not recommended
  2. Console. log (myglobal); // "hello"
  3. Console. log (window. myglobal); // "hello"
  4. Console. log (window ["myglobal"]); // "hello"
  5. Console. log (this. myglobal); // "hello"

Global Variables

The problem with global variables is that your JavaScript Application and all the code on the Web page share these global variables. They live in the same global namespace, therefore, when two different parts of the program define global variables with the same name but different roles, naming conflicts are inevitable.

The web page contains code that is not written by the page developer. For example:

◆ Third-party JavaScript Library

◆ Script code of the advertiser

◆ Third-party User tracking and analysis script code

◆ Different types of widgets, logos, and buttons

For example, the third-party script defines a global variable called result. Then, you define a global variable named result in your function. The result is that the subsequent variables overwrite the previous ones, and a third-party script will immediately fart!

Therefore, it is important to use as few global variables as possible if you want to become a good neighbor with other scripts. Some strategies mentioned later in the book to reduce global variables, such as namespace mode or automatic execution of functions, but the most important thing to reduce global variables is to always use var to declare variables.

Due to the two features of JavaScript, it is unexpected to create a global variable unconsciously. First, you can use variables without even declaring them. Second, JavaScript has an implicit global concept, meaning that any variables you do not declare will become a global object attribute. Refer to the following code:

 
 
  1. Function sum (x, y ){
  2. // Not recommended Syntax: Implicit global variables
  3. Result = x + y;
  4. Return result;
  5. }

The result in this code is not declared. The code works normally, but after calling a function, you have an extra global namespace in the final result, which can be the root cause of the problem.

The empirical rule is to always use var to declare variables, as demonstrated by the sum () function of the short version:

 
 
  1. function sum(x, y) {  
  2.    var result = x + y;  
  3.    return result;  

Another inverse example for creating an implicit global variable is to use the task chain for partial var declaration. In the following snippet, a is a local variable but B is indeed a global variable, which may not happen as you wish:

 
 
  1. // Inverse example, do not use
  2. Function foo (){
  3. Var a = B = 0;
  4. //...
  5. }

The reason for this phenomenon is that the value is assigned from right to left. First, the value assignment expression B = 0. In this case, B is not declared. The return value of this expression is 0, and then this 0 is assigned to the local variable a defined through var. In other words, you enter:

 
 
  1. var a = (b = 0); 

If you are ready to declare variables, it is better to use chain allocation without generating any unexpected global variables, such:

 
 
  1. Function foo (){
  2. Var a, B;
  3. //... A = B = 0; // both local variables
  4. }

However, another reason to avoid global variables is portability. If you want your code to run in different environments (under the host), use global variables such as thin ice, because you will accidentally overwrite host objects that do not exist in your initial environment (you thought the name could be used with confidence, but it is not applicable in some cases ).


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.