JavaScript Advanced: How to Write Elegant JavaScript Code

1. Maintainable code

Generally speaking, the code is maintainable means that it has the following characteristics:

  1. Easy to understand, no need to ask the original developer, anyone can see what the code does and how it is implemented;
  2. In line with common sense, everything in the code seems logical, no matter how complicated the operation;
  3. Easy to adapt, even if the data changes, it does not need to be completely rewritten;
  4. Easy to expand, the code structure has been carefully designed to support future expansion of core functions;
  5. Easy to debug, when there is a problem, the code can give clear information, and it can directly locate the problem;

2. Coding Specifications - Readability

To make code easy to maintain, it must first be made readable. Code indentation is an important basis for ensuring readability. If everyone uses the same indentation, the code of the entire project will be easier to understand. Indentation is usually defined using the number of spaces instead of the tab key, because the tab key is displayed differently in different text compilers, and generally the indent is 4 spaces.
Another aspect of readability is code comments. In most programming languages, it is widely accepted practice to write comments for each method.
In general, comments should be written in the following places:

  1. Functions and methods, each function and method should be commented to describe its purpose, and the algorithm used to accomplish the task. At the same time, also write clearly the premise of the function or method, the meaning of each parameter, and whether the function returns a value.
  2. Large code blocks, multiple lines of code but used to complete a single task, should be commented in front to clearly write the task to be completed.
  3. Complex algorithms, if they use a unique method to solve the problem, should be explained through annotations. This will not only help others review the code, but also help yourself review the code in the future.
  4. Use black technology, some special methods, and specific assumptions.

3. Variable and function naming

Proper naming of variables and functions in code is critical to its readability and maintainability.

  1. variable name should be name;
  2. Function names should start with a verb;
  3. Variables, functions, and methods all start with a lowercase letter and use camel case;
  4. The name should be as descriptive and intuitive as possible, but not too verbose;

Fourth, loose coupling

Whenever one part of an application depends too tightly on another, the code becomes tightly coupled and thus difficult to maintain.
A typical problem is that one object has a direct reference to another, so that modifying one may have to modify the other. Tightly coupled software is difficult to maintain and will definitely require frequent rewrites.

1. Decouple HTML and JavaScript

The most common coupling in web development is HTML and JavaScript. In web pages, HTML and JavaScript represent solutions at different levels. HTML is data and JavaScript is behavior. This is because for them to interoperate, the two technologies need to be linked in different ways. Unfortunately, some of these ways lead to tight coupling of HTML and JavaScript.
Embed JavaScript directly in HTML, or use a

<!-- 使用<script>造成紧密耦合 -->
<script>
	document.write("hello 哪吒编程");
</script>

<!-- 使用事件处理程序属性造成紧密耦合 -->
<input type="button" value="Click me" onclick="dosomething()"/>

While this is technically fine, in practice it tightly couples the HTML that represents the data with the JavaScript that defines the behavior. Ideally, the HTML and JavaScript should be completely separate, with JavaScript being imported through an external file and then added using the DOM behavior.
In general, creating large amounts of HTML in JavaScript should be avoided. Again, this is mainly to ensure that the data layer and the behavior layer perform their respective functions, and it is easier to locate the problem when something goes wrong.

2. Decouple CSS and JavaScript

Another layer of a web application is CSS, which is responsible for styling the page.
JavaScript and CSS are closely related and both build on top of HTML, so they are often used together.
An example where CSS and JavaScript are closely linked:

element.style.color = "red";
element.style.backgroundColor = "blue";

3. Decouple application logic and event handlers

Every web application has a large number of event handlers listening for various events. However, very few of them can separate application logic from event handlers.
Here are some points you should be aware of when decoupling application logic and business logic:

  1. Do not pass the event object to other methods, but only pass the necessary data in the event object;
  2. Every possible operation in the application should be performed without event handlers;
  3. Event handlers should handle events and leave subsequent processing to the application logic;
    doing the above can give a huge boost to the maintainability of any code, as well as open up a lot of possibilities for future testing and development.

5. Coding Conventions

1. Respect object ownership
2. Do not declare global variables
At most one global variable can be created as a namespace for other objects and functions.
3. Don’t compare null
4. Use constants

  1. repeated value
  2. user interface string
  3. URL
  4. any value that may vary

6. Scope awareness

As the number of scopes in the scope chain increases, so does the time required to access variables outside the current scope chain, accessing global variables is always slower than accessing local variables because the scope chain must be traversed, any suspicious shortening of the traversal effect Domain chain time initiatives can improve code performance.

1. Avoid global lookups

One of the very important things to improve the performance of your code is probably to beware of global lookups. Global variables and functions are always the most time consuming compared to local variables because of scope chain lookups.
If the document is referenced multiple times in the for loop, the performance of this function can be significantly improved by saving the reference to the document object in the local scope, since only the scope chain lookup is required.

2. The with statement is not applicable

In performance-critical code, the with statement should be avoided. Similar to a function, the with statement creates its own scope and therefore lengthens the scope chain of the code within it. The diamagnetic inside the with statement must be slower than the code executed outside it because of one more step in the scope chain lookup.

Seven, optimize the cycle

Loops are syntactic constructs commonly used in programming, so are very common in JavaScript, optimizing these loops is an important part of performance optimization, because the loop will run the same code multiple times, so the running time will automatically increase.

1. Simplify termination conditions

It should be as fast as possible because the termination condition is computed each time the loop is looped.

2. Simplify the loop body

The loop body is the most time-consuming part, so try to optimize it as much as possible. Make sure it doesn't contain intensive computations that can easily be moved outside the loop.

3. Test cycle after use

The most common loops are for and while loops, both of which are test-first loops. do-while is a post-test loop that avoids initial evaluation of the termination condition and is therefore faster.

4. Unroll the loop

If the number of loops is limited, it's usually faster to ditch the loop and just call the function multiple times.

8. Minimize sentences

The number of JavaScript code statements affects the speed of execution. A statement that can perform multiple operations is faster than multiple statements that perform one operation each. Then the goal of optimization is to find statements that can be combined to reduce the execution time of the entire script.

1. Multiple variable declarations

2. Insert iterative values

Whenever you use iterative values ​​(increment or decrement), use composite statements whenever possible.
e.g.
let name = values[i++]
substitute

let name = values[i];
i++;

3. Use arrays and object literals

Nine, optimize DOM interaction

In all JavaScript code, the part that involves the DOM is undoubtedly very slow. DOM manipulation and interaction takes a lot of time, as the whole or part of the page needs to be re-rendered frequently. Also, seemingly simple operations can take a long time because of the large amount of information carried in the DOM. Understanding how to optimize DOM interactions can greatly speed up script execution.

1. Minimize real-time updates

When accessing the DOM, as long as the accessed part is part of the displayed page, it is performing a real-time update operation. It's called a live update because it involves updating the display of the page immediately for the user to see. Every such update, whether to insert a character or delete a piece of content on the page, incurs a performance penalty. This is because the browser needs to recalculate thousands of metrics for this before it can perform the update. The more real-time updates, the longer it takes to execute the code.

2. Use innerHTML

There are two ways to create new DOM nodes in a page, using DOM methods such as createElement() and appendChild(), and using innerHTML. For a small number of DOM updates, there is little difference between the two techniques, but for a large number of DOM updates, using innerHTML is much faster than creating the same structure using standard DOM methods.
When assigning a value to innerHTML, an HTML parser is created in the background, and the DOM structure is created using native DOM calls instead of JavaScript's DOM methods, which are faster because they execute compiled code instead of interpreted code.

3. Use delegated events

Most web applications make heavy use of event handlers for user interaction. The number of event handlers in a page is directly related to the speed at which the page responds to user interactions. In order to reduce the impact on page responses, event delegation should be used as much as possible.
Event delegation takes advantage of the bubbling of events, and any bubbling event can be handled not on the event target, but on any ancestor element of the target. Based on this knowledge, event handlers can be added to higher-level elements responsible for multiple targets. Whenever possible, event handlers should be added at the document level, since events for the entire page can be handled at the document level.

4 HTMLCollection

Because web applications have great performance problems, as long as the HTMLCollection is accessed, whether it is its properties or methods, it will trigger the query document, and this query is quite time-consuming. Reducing the number of visits to the HTMLCollection can greatly improve the performance of the script.
The most critical place to optimize HTMLCollection access is looping.

10. JavaScript Mind Map

insert image description here

Pay attention to the public number: Nezha programming

Nezha programming updates high-quality articles every week. After paying attention, reply to [CSDN] to receive Java mind maps, Java learning materials, and massive interview materials.

 

Add me WeChat: 18525351592

Pull you into the technical exchange group, there are many technical bigwigs in the group, exchange technology together, advance together, enter the big factory together, and also buy technical books for free~~

Guess you like

Origin blog.csdn.net/guorui_java/article/details/123970061