Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Which Javascript tips can improve code quality?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Which Javascript tips can improve code quality, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

There are many common ways of optimizing and refactoring code in Javascript. Here are 11 Javascript tips to help you improve your code quality.

1. Refinement function

Benefits:

Avoid oversized functions.

Independent functions help code reuse.

Independent functions are more likely to be overridden.

If a stand-alone function has a good name, it itself acts as an annotation.

Semantic implementation of multi-segment separate logic in different functions can make the code logic clear and clearly see what is being done at each step.

Code example:

The implementation acquires the data, then operates the dom to display the data, and finally adds events

Before function refinement

/ / the logic is written together. You need to read all the logic to know what this code is for. Local logic cannot reuse function main () {$.ajax.get ('/ getData'). Then ((res) = > {const ul = document.getElementById ('ul'); ul [XSS _ clean] = res.list.map (text = > `$ {text} `). Join ('\ n') Const list = document.getElementsByClassName ('li'); for (let I = 0; I

< list.length; i ++) { list[i].addEventListener('focus', () =>

{/ / do something});});}

After function refinement

Function getData () {return $.ajax.get ('/ getData'). Then ((res) = > res.data.list);} function showList (list) {const ul = document.getElementById ('ul'); ul [XSS _ clean] = list.map (text = > `${text}`). Join ('\ n');} function addEvent () {const list = document.getElementsByClassName ('li'); for (let I = 0; I

< list.length; i ++) { list[i].addEventListener('focus', () =>

{/ / do something});}} / / the logic is clear, and some extracted functions can be reused async function main () {const list = await getData (); / / get data showList (list); / / display page addEvent (); / / add events}

two。 Merge duplicate conditional clips

If there are some conditional branch statements in the body of a function, and some repeated code is scattered inside these conditional branch statements, then it is necessary to merge and deduplicate.

/ / pre-merge function main (currPage) {if (currPage = totalPage) {currPage = totalPage; jump (currPage); / / Jump} else {jump (currPage); / / Jump}}; / / merge function main (currPage) {if (currPage = totalPage) {currPage = totalPage;} jump (currPage); / / separate jump function}

3. Refine the conditional branch statement into a function

Complex conditional branching statement is an important reason why the program is difficult to read and understand, and it is easy to lead to a huge function. Sometimes conditional branch statements can be refined into semantic functions to make the code more intuitive and logical.

/ / function getPrice (price) {var date = new Date (); if (date.getMonth () > = 6 & & date.getMonth () = 6 & & date.getMonth () = 0) {return 'opera';} else if (str.includes (' msie')) {return 'ie';} else {return' other';}} / / cycle judgment, abstract the corresponding relationship as configuration, and make function getBrowser () {const str = navigator.userAgent more clear and clear. Const list = [{key: 'QQBrowser', browser:' qq'}, {key: 'Chrome', browser:' chrome'}, {key: 'Safari', browser:' safari'}, {key: 'Firefox', browser:' firefox'}, {key: 'Opera', browser:' opera'}, {key: 'msie', browser:' ie'} ] For (let I = 0; I < list.length; iTunes +) {const item = list [I]; if (str.includes (item.key)) {return item.browser};} return 'other';}

5. Let the function exit in advance instead of the nested conditional branch

Change the function to multiple exits and return ahead of time, replacing the nested conditional branch.

Function del (obj) {var ret; if (! obj.isReadOnly) {/ / if it is not read-only, if (obj.isFolder) {/ / if it is a folder ret = deleteFolder (obj);} else if (obj.isFile) {/ / if it is a file ret = deleteFile (obj);}} return ret;} Function del (obj) {if (obj.isReadOnly) {/ / reverse if expression return;} if (obj.isFolder) {return deleteFolder (obj);} if (obj.isFile) {return deleteFile (obj);}}

6. Pass object parameters instead of an overly long parameter list

If the function parameters are too long, it will increase the risk of error. It is troublesome to ensure that the order of transmission is correct, and the readability of the code will become worse. Try to ensure that the parameters of the function will not be too long. If more than one parameter must be passed, it is recommended to use an object instead.

Generally speaking, it is best to have no more than 3 function parameters.

Function setUserInfo (id, name, address, sex, mobile, qq) {console.log ('id=' + id); console.log ('name=' + name); console.log ('address=' + address); console.log ('sex=' + sex); console.log ('mobile=' + mobile); console.log ('qq=' + qq);} SetUserInfo (1314, 'sven',' shenzhen', 'male',' 137 cycles, 377876679); function setUserInfo (obj) {console.log ('id=' + obj.id); console.log ('name=' + obj.name); console.log ('address=' + obj.address); console.log ('sex=' + obj.sex); console.log ('mobile=' + obj.mobile) Console.log ('qq=' + obj.qq);}; setUserInfo ({id: 1314, name: 'sven', address:' shenzhen', sex: 'male', mobile:' 137 stories, qq: 377876679})

7. Reduce the use of ternary operators

The trinomial operator has high performance and less code.

However, ternary operators should not be abused. We should use them in simple logic branches and avoid them in complex logic branches.

/ / simple logic can use the ternary operator var global = typeof window! = = "undefined"? Window: this; / / complex logic is not suitable to use var ok = isString? (isTooLang? 2: (isTooShort? 1: 0):-1

8. Rational use of chained calls

Advantages: chain calls are easy to use and have less code.

Disadvantages: the disadvantage of chain calls is that it is not convenient to debug. If we know that there is an error in a chain, we have to disassemble the chain before we can add some debugging log or add breakpoints, so that we can locate the place where the error occurs.

If the structure of the chain is relatively stable and it is not easy to modify in the later stage, the chain type can be used.

Var User = {id: null, name: null, setId: function (id) {this.id = id; return this;}, setName: function (name) {this.name = name; return this;}}; User .setId (1314) .setName ('sven'); var user = new User (); user.setId (1314); user.setName (' sven')

9. Decompose large classes

The decomposition of large classes is very similar to the refinement of functions, in which the logic of the class is not clear and difficult to understand and maintain.

Reasonable large class decomposition can make the logic of the class clear, and sub-modules can be easily reused.

10. Active bit operator

The performance of multiplication and division is not high in programming languages, but the performance of multiplication and division can be improved by using bit operators in some cases.

11. Pure function

A pure function is a function that does not depend on and does not change the state of variables outside its scope.

The return value of a pure function is determined only by the parameters when it is called, and its execution does not depend on the state of the system (execution context).

If you have the same input parameters, you will get the same output, that is, there are no random variables that will affect the output.

Characteristics that do not belong to pure functions:

Change the file system

Insert records into the database

Send a http request

Variable data

Print / log

Get user input

DOM query

Access system statu

The role of pure functions:

Reliability: function returns are always the same as expected

Cacheability: because as long as the input is the same, the output must be the same, so you can use the input as the key, the output as the value, and use the object to cache the calculated results

Portability: because there are no external dependencies, porting to any environment works correctly

Testability: make it easy to do unit tests for functions

Parallelism: for some complex computing, parallel computing can be done (for example, multiple tasks can be computed in parallel using multiple sub-processes of nodejs to improve computing speed)

Application scenarios:

It is best to use pure functions for tool functions.

Code used on multiple platforms (nodejs, browser, WeChat Mini Programs, native client, etc.)

Relatively independent function

Var a = 1; / / function sum (b) {return a + b;} / / function sum (b) {a = 2; return b;} / / function sum (b) {return b + Math.random ();} / / function sum (b, c) {return b + c } after reading the above, have you mastered any Javascript tips to improve the quality of your code? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report