How to compile beautiful JavaScript code?

Source: Internet
Author: User
Abstract:The beauty of the heart, all people. Even for a piece of Common Code, how can we write the code with clear thinking and friendly functions to ensure the structure is clear, clean, and beautiful?

Many years ago, people paid attention to how functions are implemented. Nowadays, with the development of Web and Internet technologies, functions have only become the most basic requirement. How to write beautiful and neat code has become an indispensable condition for a great programmer.

A front-end development engineer asked zhihu: "I am a front-end development engineer who has two years of experience in writing JavaScript. I recently wrote some modules on some pages and found that I was always very clear when I was thinking about them, but I felt that the code was getting messy and it looked like a shit, I have a bit of code cleanliness, and I don't want to continue looking at the increasingly messy code. What should I do ?" He also developed his own JavaScript code:

In the face of such knowledgeable, studious, and enterprising programmers, our netizens are also very powerful. They not only made a comprehensive comment on his code, but also put forward some very reasonable suggestions, the following are some wonderful answers from some netizens on zhihu. Let's take a look at them:

The cloud of Changtian:

I think writing code is almost the same as writing an article: neat, elegant, and repetitive. The following are some suggestions:

Attitude

Have feelings for the Code, every line should be done with the utmost effort, and there must be an impulse to rewrite the code that throws the garbage basket twice-once this impulse happens, nothing will stop you, even when eating and drinking Lazarus, the problem will pop up in your mind, and you will solve them involuntarily ...... It is a great task to doubt your code! Come on!

Write less code

Early design can help you write less code and enhance the global sense. While writing less code can also prevent getting out of control-when you feel wrong, you should stop and free up time to think about why it deviates from the first idea. All symbols are yours. At first glance, there are too few spaces. We recommend three tools for you:

  1. Beauw.javascript or HTML can format your code. Remember to use the diff tool to compare the difference before and after formatting;
  2. Sublimelinter can provide a jshint prompt dynamically during writing (highlighting error lines );
  3. Grunt can provide a shint check (sound and desktop notification) When the file is changed );

Once the lint verification is used as a necessary process for code submission, the layout will be substantially improved.

Practice

  1. The comment symbol '//' should be empty;
  2. To prevent variable escalation, declare the variable and use it first (jshint will remind '_ height' of variable escalation and unused errors after definition );
  3. Hard encoding should not be used and repeated several times (ID extension names can be defined in constants, with uppercase letters );
  4. There should not be two configuration properties, which have unknown meanings (this. opts and this. _ options );
  5. If the attribute of the same object is referenced more than twice, you should define a local variable and then reference it (VAR Options = This. _ options );
  6. Two attribute naming styles (colmodel and table_body) should not be used at the same time );
  7. The local variable name should be as short as possible, and the method name should be as complete as possible (both fromattpl and parsetemplate should not be available );
  8. The local variable name does not need to start with an underscore. It is only necessary for the object's private attributes and private methods;
  9. Variable names do not need to contain type attributes (_ thdoms is called THS );
  10. When Javascript is used, the for loop can be basically avoided (for example, jquery has high-order functions such as $. Each, $. Map, $. filter, $. grep, and so on );
  11. Jquery object names start with $ to distinguish DOM objects;
  12. Use ontext (for example, this. $ table =$ ('table', this. $ element) whenever possible for jquery queries ));
  13. Jquery Dom operations and native DOM operations should not be mixed (when jquery is already used, jquery should be used to operate the Dom to avoid ugly native operations );
  14. The Dom element is constructed and should not be searched in the document again (the structure on the graph is too complex to understand at a Glance );

Code Review

Writing the program correctly is only the first step. It is the best way to learn and improve your code together with your colleagues and friends.

Dion:

Code style and Layout

Although no language has any agreed style, there are always unwritten and popular customs. Take your code as an example and give the following style suggestions:

  • There is one more blank line between each function. Yes, there are more blank lines except comments;
  • Add spaces, such as spaces between the IF and the parentheses, between the parentheses and the curly braces, and between the colon and function;
  • The style is consistent. In your code, there are spaces between the plus signs and arithmetic numbers, while others do not;
  • Names of variables starting with less underscores;
  • In a piece of code, the VaR statements can be combined;
  • Functions or objects that will not be modified for the time being are collapsed by using the editor, which looks much more neat;
  • The editor style of the black background is good, but the keywords, comments, operators and other colors can be adjusted, mainly to prevent Aesthetic Fatigue, change the tone to change the mood;

Use a sophisticated JavaScript Library

If it is correct, you may have used jquery (at least there is a parser similar to sizzle or a simpler one, and the evidence is around the last 10 lines ). Therefore, try to avoid using native Javascript DOM operations.

The $ symbol of jquery replaces various getelement (s) byxxx interfaces in a unified CSS selector style and has high scalability. It is a comprehensive use of many design patterns.

Of course, native DOM also has its own advantages (mainly execution efficiency), but most of the time, jquery is the best choice for tradeoff, which is development efficiency, code quality, and execution efficiency. We also recommend the Javascript MVC library and jquery UI library.

Code sorting

The idea is clear, and then write the code, you have done it.

But who can ensure that the Code is static and permanent?

Therefore, in "refactoring", unless it is time-consuming, never let down the quality of the Code.

Toobug, a Web Front-end enthusiast, also gave a detailed comment on the landlord's code and gave some very meaningful guidance:

  1. The logic in the Code is not segmented, there are no blank lines, no comments, and looks tired. We recommend that you block the Code. For example, you can set variables in the header and then process some values, finally, execute some other functions. In this example, there are many inconveniences. For example, you can first VaR _ height and then assign values in the condition branch. For example, a parsetemplate is included in a bunch of values.
  2. "_" Is used too much, this. _ VaR can be understood because it is necessary to identify whether a private variable is needed, but there is no need to add the VaR _ height variable. If it is added too much, it looks very tired and does not make any difference.
  3. The common variables are not cached. This. _ options should be the most cached here. Otherwise, it may seem messy and it is also good for performance.
  4. The planning (naming) of objects is unclear. For example, what is the relationship between this. _ options and this. opts? I cannot understand it.
  5. The Code style is not uniform. For example, the access object is always this. _ options. Height. Why does this. _ options. Data ['head'] come out later? Isn't it clearer to use this. _ options. Data. Head?
  6. Variable names in the function are chaotic (similar to the fourth point). For example, what is the relationship between ID and _ ID in the second function? Why not use AAAID and bbbid? What is 'cre'? Is it the abbreviation of createelement? Variables should be meaningful and distinguished names as much as possible.
  7. The function name table is not clear and does not comply with most of the conventions. First, we can see _ ishavetable. My first reaction is that it should be like return true or return false. As a result, if it is so long, will it be returned later? I took another look at it, and there was no return! Why do we need _ ishavetable? A function starting with _ Is should return either true or false clearly.

The above is a wonderful answer. Keep proper spaces and styles, and use naming rules that are customary. For example, the local variable name should be as short as possible, and the method name should be as complete as possible.

What tricks do you have for netizens? Let's discuss it with us!

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.