preface
Have you ever cursed the “ex” code? Has your code ever been teased? No comments, arbitrary naming, no encapsulation, chaotic structure, thousands of lines per page…
How to write elegant code, so that they are not ridiculed, let people envy, next we talk about how to write elegant code, if you have better writing method and experience, welcome to leave a comment, learn together
What is elegant code
We talk first, what kind of code is elegant, in my opinion, elegant code includes the following aspects, the first is the code of concise, can resolve the use of a single line of code, don’t write two or more, then it is easy to read, is not only used to let the machine code (server, the browser) to run, but need to write of choose and employ persons, maintenance, May be oneself, can also be colleagues now, future colleagues, this is the maintainability of the code, another is we are focused on is the performance, like we often write cycle, when meet business function condition, less of a cycle is less a cycle, there is no longer use a reference to the type of data, to timely manual for the release of memory, (although there is a garbage collection mechanism), but would it be better to free memory earlier
annotation
Comments, writing code without comments, especially elegant code, not to mention comments; Comments are for people to read, maybe for themselves, maybe for colleagues and future colleagues (this sentence has been said many times), so why do we write comments, and how to write comments? Let’s talk about comments first
How do I use comments? (Where to add comments)
The general rule is to add comments when the code is not clear, which I think includes the following aspects:
- Add comments to code that is difficult to understand (logic is complex, nesting levels are high, passing parameters are not obvious, etc.)
2. Code that can be mistaken for something wrong (code that doesn’t follow the normal pattern 3. The state of data (take the order state as an example, the order may have many states, at this time, when writing the leaf logic of this paragraph, the meaning of different states should be written up, so that future maintenance or new people can get started more quickly when receiving the project) 4. Other comments (document comments, variable comments, function comments)
1. Document Notes:
Simple description of the current JS file function, is the page JS logic processing, or public methods
If it is a VUE project, it describes the role of the current VUE file,
2. Variable notes:
Say what the variable is used for, name it semantically, comment it if you need comment it, okay
// difference
let uName = 'Symbol.; // The hump is used. You can't intuitively see what the variable means
// grace
let userName = 'Symbol.; // Semantically named, not too abbreviated
Copy the code
3. Function comments
Parameter comments include the parameter’s data type, parameter name semantics, return parameter comments include the default value, has returned the parameter’s data type
Such as:
/ * * *@description: second way to detect data types *@param {any} Data to detect the variable * of the data type@return {string} Type Returns the specific type name (lowercase) */
export const $typeOf = (data) = > {
return Object.prototype.toString.call(data).replace(/\[object (\w+)\]/.'$1').toLowerCase()
}
Copy the code
You can download koroFileHeader from vscode’s plugin marketplace to install it and generate comment formats with one click
variable
Rules for defining variables: use lowercase variables (let for declaring variables), uppercase constants (const for declaring constants), semantically name variables, specify data types of variables, avoid using too many global variables, declare variables first, use them later
1. Let and const replace var
Define constants
// difference
var myLove = 'My love is Code';// It is not named const, and the constant name is not fully capitalized
// grace
const MY_LOVE = 'My love is Code';
Copy the code
Using the var keyword defined constants can be change, that is, we define a constant, can also assign a value to it to change the constants, and then according to the specification in our in the program, in a statement after a constant, the constants in the entire program is global is not able to be changed again, so declare a constant, Const const const const const const const const const const const const const const
We’re talking about strings in constant declarations, so let’s look at what specifications and code we need to pay attention to when using string constants
// Be careful. Static strings use single or backquotation marks (template strings) instead of double quotation marks. Dynamic strings use backquotation marks and do not use + to concatenate strings
// difference
const name = "Symbol卢";
const say = 'My name is' + name + 'and I love FE';
// grace
const NAME = 'Symbol.;
const b = `My name is ${ NAME } and I love FE`;
Copy the code
Define variables
Let is used for local variables and VAR is used for global variables. One rule to remember is that variables are only declared in the code block in which they are declared
if (true) {
let x = 'hello';
}
let name = () = > {
// ...
}
Copy the code
// difference
one.js
window.name = 'Symbol.;
two.js
window.name = 'Jack lee';
three.js
window.name = 'Leo';
Copy the code
Defining global variables in the Window object is easy to pollute the global environment. In ordinary work, many people cooperate, there is likely to be a small surprise. Therefore, we should be cautious and cautious
Assign a constant
let lastName = fullName[1]; // fullName=[], fullName[1]=undefined
let propertyValue = Object.attr; // If Object={}, object.attr =undefined
Copy the code
For reference data types (as well as data returned from interfaces), take care (default values if there is no data) how can you be sure that there is a value in it?
let lastName = fullName[1] | |' '
let propertyValue=Object.attr || 0
Copy the code
(1) Write code to define variables according to strong type style to specify the type, and after the declaration of variables, do not arbitrarily change the data type of variables, change the change may cause problems
// Suppose we declare three variables a,b, and c
let a,b,c; // difference, the variable is defined without specifying the type
let a = "", b = [], c = {}; // good
// difference
let a = ""; . a =100; // Changed the type of a variable when defining it.
let b = 5; . b =200; // Once grace has defined the data type, do not change it
Copy the code
2. Avoid using == to make logical judgments (don’t mine your own code)
As we all know, JS is a weak type of language, expression assignment operations and other operations will also lead to data type conversion,
== means true as long as the values are equal. === requires not only the values to be equal but also the type to be the same
But what were the rules before them? Let’s talk more about data types in JS in the next article;
Use of == sometimes does not achieve the desired results, hidden dangers, take a look at the following situations (you taste, you taste)
0= =' ' // true
0= ='0' // true
' '= =0 // true
' '= ='0' // false
false= ='0' // true
false= ='false' // false
false= =undefined // false
false= =null // false
null= =undefined // true
true= =1 // true
Copy the code
If the data type of this variable is determined, then there is no need to use == how coincidence an equal sign, to give the program more protection, and free of money, afraid of what? Dry is done; When judging debugging, use ===, the data type is not sure how to do ,,,, (whisper force, data type is not sure, then move rich hand, convert the data type bai)
If the data type of the variable is not determined, we can manually convert it to be determined
let total = "6";
if(total == 6) {} // difference
if(parseInt(total) === 6) {}// grace manually convert the data type
Copy the code
An array of
It is recommended to use the new syntax in ES6+ when operating on arrays
// Array copy
// difference
let items=['1'.'2'.'3'];
let items2=['4'.'5'.'6'];
for (i = 0; i < items.lenght; i++){
items.push(items2[i]);
}
// grace
const itemsCopy = [...items];
// Extend the operator abbreviation
// joining arrays
const odd = [1.3.5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1.2.3.4];
const arr2 = arr.slice()
// joining arrays
const odd = [1.3.5 ];
const nums = [2 ,4 , 6. odd];console.log(nums); // [2, 4, 6, 1, 3, 5]
// cloning arrays
const arr = [1.2.3.4];
const arr2 = [...arr];
Copy the code
- When assigning to a variable using an array member, destruct assignment is preferred.
const Arr = [1.2.3.4];
// difference
const first = Arr[0];
const second = Arr[1];
// grace
const [first, second] = Arr; // There are simple ways. It's gotta be the easy way
Copy the code
function
Function is used in our work very much, but how to write elegant function? Function naming, function input parameter, parameter verification, function output parameter, etc.
Function naming
Function naming, we first need semantic (functional naming, that is to say, the function is born for what), such as: return Boolean function should start with is/can/has and other words, can let people more intuitive understanding of the function; The data in the get interface is named using the get prefix.
let isEmpty = () = >{... }let canCreateDocuments = () = >{... }let hasLicense = () = >{... }// Do not name functions with negation syntax
//difference
let isNotSupport = () = > {};
let canNotUpdate = () = > {};
// grace
let isSupport = () = > {};
let canUpdate = () = > {};
Copy the code
Action functions begin with a verb
let sendEmailToUser = (user) = >{... }let geUserInfo = (user) = >{... }let setUserInfo = (user) = >{... }Copy the code
Use the arrow function in preference
Arrow functions are much cleaner than traditional functions and are bound to this (the arrow function does not change the direction of this).
let arr [18.19.20.21.22.23.24.25]
// commonly
function findAge (arr, age) {
return arr.filter(function (num) {
return num === age
})
}
// Doesn't Grace look more elegant
let findAge = (arr, age) = > arr.filter(num= > num === age)
Copy the code
The input parameter to the function
Function entry parameters, is to enable users, when calling the function, can more clearly pass the parameters needed by the function to the function, is not prone to occur, parameter transfer error (parameter order is reversed, etc.) some low-level, and difficult to find problems.
// difference
function getImages(api, true.false); // What does true and false mean? Without a comment, it looks confused
// grace
function getImages({
imageApi: api,
includePageBackground: true.//At a glance, you know thistrueandfalseCompress:false,})
Copy the code
Receive parameters
If the argument to a function is an object, destruct assignment is preferred
// Assume that the current scenario is to get the current and former names of the user's information
// difference
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// commonly
function getFullName(obj) {
const { firstName, lastName } = obj;
}
// grace
function getFullName({ firstName, lastName }) {}// grace gives it a default value
function getFullName({firstName, lastName = 'no'}) {}// The parameter name is too long, let's rename it to simplify
// grace
function getFullName ({firstName: first, lastName: last}) {}Copy the code
Parameter calibration
Less nesting, return as soon as possible if the condition is not met, reduce nesting as much as possible, the fewer nested levels, the more concise and elegant the function looks,
function test(name, sex = 1) {
if(! name){// Throw an error as soon as possible if the condition is not met
throw new Error('Name argument not passed');
}
// ...
}
Copy the code
The output parameter of the function
If a function returns multiple values, it is recommended to use an object as the return value rather than an array. Why?? Because objects serve as return values, it is easier to add return values later and change the order of return values, which is more flexible and easier to expand than arrays
// If the data type of the returned parameter is fixed,
// difference returns different data types
function getResult(cont) {
if(count < 0) {
return "";
} else {
return count * 10; }}// grace
function getResult(cont) {
if(count < 0) {
return -1;
} else {
return count * 10; }}// The function returns multiple values. It is recommended to use an object as the return value of the function
// commonly
function processInput(input) {
return [left, right, top, bottom];
}
// grace
function processInput(input) {
return { left, right, top, bottom };
}
const { left, right } = processInput(input);
Copy the code
Execute function immediately
It is also recommended to write immediate functions in the form of arrow functions. First, it’s simpler, and it’s bound to this (the arrow function doesn’t change the direction of this).
(() = > {
console.log('If you feel this article is ok, please like + follow + forward'); }) ();Copy the code
Functional programming is preferred
// difference
for(i = 1; i <= 10; i++) {
a[i] = a[i] +1;
}
// grace
let b = a.map(item= > ++item) // Is it more concise
Copy the code
Excessive use of if else..
Note: in order to facilitate you to see the optimized format, this is a random use of a to memorize the syntax structure.
// commonly
if (a === 1) {
/ /...
} else if (a ===2) {
// ...
} else if (a === 3) {
/ /...
} else {
/ /...
}
/ / the general
switch(a) {
case 1:
//....
case 2:
//....
case 3:
//....
default:
//....
}
// grace === "Object
const fruit = {
1: ['1'.'11'].2: ['2'.'22'].3: ['3'.'33']};let test = (a) = > {
return fruit[a] || [];
}
// grace ===》》》 Map
const fruit = newMap()
.set('Joe'['Zhang SAN Feng'.'Zhang Sanli'])
.set('bill'['Li Wei'.'Li So Li'])
let test = (a) = > {
return fruit.get(a) || [];
}
// grace === filter
const fruits = [
{ name: 'Joe'.work: 'js' },
{ name: 'bill'.work: 'php' },
{ name: 'Cathy'.work: 'java'},];let test = (a) = > {
return fruits.filter(item= > item.name === a);
}
// Grace === "strategy mode
let handler = {
1: () = > {
//....
},
2: () = > {
//....
},
3: () = > {
//....
},
default: () = > {
//....
}
}
handler[a]() || handler['default'] ()Copy the code
Warm tips
A single function does a single function, not multiple functions. There is a very important principle in project development. The single principle is that a single function (file) does only one thing, and in development, no project is finished. You need to keep updating and maintaining, so the single rule is for development and maintenance, don’t have a function that’s both parent and parent, because the coupling is too high to maintain
other
The determination of array length in if
// difference
if(arr.length ! = =0) {
/ /...
}
// grace
if (arr.length) {
/ /...
}
// difference
if (arr.length === 0) {
/ /...
}
// grace
if(! arr.length) {/ /...
}
Copy the code
Logical operator
if (a === 1) {
b()
}
// Can be written as
a === 1 && b()
const arr = [1.2.3];
if(! arr.length){ b() }// Can be written
arr.length || b()
// THEREFORE, I am sure that THE keys I rely on exist, so I therefore avoid the error 'XXX of undpay'
let user = {
name: 'Symbol..age: 18.children: {
name: 'Little Symbol Lew'}}let childrenName = user.children && user.childre.name
Copy the code
If you can use the ternary operator (ternary operator), use it
// difference
const a = ' ';
let b;
if( a === ' ' ){
b = 'no'
} else {
b = 'ok'
}
const a = ' '
let b = a ? 'no' : 'ok'; // 'ok'
Copy the code
If (a)/if(!); if(a)/if(! A) form. When the type is array or object, you can use the form if(an instanceof array) or if(an instanceof String). Here is also a function for datatype determination that I wrote earlier
/ * * *@description: second way to detect data types *@param {any} Data to detect the variable * of the data type@return {string} Type Returns the specific type name (lowercase) */
export const isTypeOf = (data) = > {
return Object.prototype.toString.call(data).replace(/\[object (\w+)\]/.'$1').toLowerCase()
}
Copy the code
Imperative programming is preferred for for loops
// difference
let result=[]
let numberArr=[1.2.3.4.5.6]
for(i = 1; i <= 10; i++) {
if(numberArr[i]>4){
result.push(numberArr[i])
}
}
Copy the code
Use imperative programming preferentially, such as find, some, every, map, filter, etc
Use Array. Includes to handle multiple | | conditions
// difference
if (a === 1 || a === 2 || a === 3 || a === 4) {
/ /...
}
// grace
let arr = [1.2.3.4]
if (arr.includes(a)) {
/ /...
}
Copy the code
Use array. every and array. some to handle all/part of the condition
// grace
const users = [
{ name: 'Joe'.sex:1 },
{ name: 'bill'.sex:2 },
{ name: 'Cathy'.sex:1}];function test() {
Condition :(short form) all users must be female
const isAllGirl = users.every(item= > item.sex === 1);
// Condition: at least one user is male
const isAnyMan = users.some(item= > item.sex === 2);
}
Copy the code
Using regular expressions
const imgType ='jpg'
if(imgType === 'jpg' || imgType === 'png' || imgType === 'gif') {console.log('is image')}// Use match to match regular expressions
const imgType='jpg'
if(imgType.match(/. *? (gif|png|jpg)/gi)) {console.log('is image')}Copy the code
Connection string
let name = 'Symbol'
let message = 'Hello,I\'m' + name + 'take care '// Use the traditional plus sign, which looks redundant and error-prone
// Emma, template character incense, really want to
let message = `Hello,I'm ${name} take care `
Copy the code
conclusion
After you’ve done a feature, ask yourself if there are other ways to write it that are more concise than the way you currently write it.
Vue-pure-admin is recommended
Brief introduction: Vue-pure-admin is a free and open source mid-backend template developed using the latest vue3, Vite2, TypeScript, element-Plus and other mainstream technologies. It is a pre-preview address for mid-backend front-end solution projects
GitHub address: vue-pure-admin
History oliver
- Talk about arrays in JS
- Using Plain English to handle regular easily (PART 1)
- Using plain English to easily solve the regular (2)
- Learn redraw and refluxing together
- Js garbage collection mechanism principle to you talk clearly
- ES11 is here. Why don’t you check it out
- Second understand js scope and scope chain
conclusion
The above is all the content of this article, I hope to help you, here you can give a thumbs-up 👍 (thumbs-up and don’t pay), also welcome everyone forward