Daily development of 26 common JavaScript code optimization schemes

fawn 2021-02-23 09:48:39
daily development common javascript code


Hello, everyone ~, I'm a fawn , official account :「 Deer animation programming 」 Original author .

After half a year, I came back , A lot of things happened during that period . I just graduated from university and came to the front line to look for a job , Also because of the special situation this year , The article has been broken for some time . Um. ~, Don't make excuses for yourself . Now it's all settled in , Start to slowly return to writing , Hope that in 2021 Grow up in the community with you in the new year !


2021 The first phase .

This article has sorted out in the daily development 26 A common JavaScript Code optimization scheme .

This article has been published in Github blog Included , Welcome all of you ~ Star, If there are deficiencies or issues, Welcome below or Github Leaving a message. !

1、NullUndefined'' Check

When we create a new variable and assign an existing variable value , I don't want to give null or undefined, We can use a simple way to assign values .

if(test !== null || test !== undefined || test !== ''){
let a1 = test;
}
// After optimization
let a1 = test || ''

2、null Value check and give the default value

let test = null;
let a1 = test || '';

3、undefined Value check and give the default value

let test = undefined;
let a1 = test || '';

4、 Null merge operator (??

Null merge operator (??) It's a logical operator , When the operands on the left are null perhaps undefined when , Returns its right-hand operand , Otherwise, return the left-hand operand .

const test= null ?? 'default string';
console.log(test);
console.log(foo); // expected output: "default string"
const test = 0 ?? 42;
console.log(test); // expected output: 0

Specific introduction can stamp this MDN

5、 Declare variables

When we want to declare multiple variables of the same type or value , We can use a short form .

let test1;
let test2 = 0;
// After optimization
let test1, test2 = 0;

6、if Multi condition judgment

When we make multiple conditional judgments , We can use arrays includes The way to achieve the abbreviation .

if(test === '1' || test === '2' || test === '3' || test === '4'){
// Logic
}
// After optimization
if(['1','2','3','4'].includes(test)){
// Logical processing
}

7、if...else Abbreviation

When there is one or two layers if...else Nesting , We can use the ternary operator to abbreviate .

let test = null;
if(a > 10) {
test = true;
} else {
test = false;
}
// After optimization
let test = a > 10 ? true : false;
// perhaps
let test = a > 10;

8、 Multivariable assignment

When we want to assign different values to multiple variables , We can use a simple shorthand scheme .

let a = 1;
let b = 2;
let c = 3;
// Optimize
let [a, b, c] = [1, 2, 3];

9、 Arithmetic operation abbreviation optimization

When we often use arithmetic operators in development , We can use the following methods to optimize and abbreviate .

let a = 1;
a = a + 1;
a = a - 1;
a = a * 2;
// Optimize
a++;
a--;
a *= 2;

10、 Effective value judgment

We often use it in development , Let's just sort it out here .

if (test1 === true)
if (test1 !== "")
if (test1 !== null)
// Optimize
if (test1)

11、 Multiple conditions (&&) Judge

We usually encounter conditional judgment followed by function execution in projects , We can use the shorthand .

if (test) {
foo();
}
// Optimize
test && foo();

12、 Multiple comparisons return

stay return Compare... Is used in , It can be abbreviated as follows .

let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return foo('test');
}
}
// Optimize
function checkReturn() {
return test || foo('test');
}

13、Switch Abbreviation

In the form of switch sentence , We can store its conditions and expressions in the form of key value pairs .

switch (type) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// ......
}
// Optimize
var obj = {
1: test1,
2: test2,
3: test
};
obj[type] && obj[type]();

14、for Loop abbreviation

for (let i = 0; i < arr.length; i++)
// Optimize
for (let i in arr) or for (let i of arr)

15、 Arrow function

function add() {
return a + b;
}
// Optimize
const add = (a, b) => a + b;

16、 Short function calls

function fn1(){
console.log('fn1');
}
function fn2(){
console.log('fn2');
}
if(type === 1){
fn1();
}else{
fn2();
}
// Optimize
(type === 1 ? fn1 : fn2)();

17、 Array merging and cloning

const data1 = [1, 2, 3];
const data2 = [4 ,5 , 6].concat(data1);
// Optimize
const data2 = [4 ,5 , 6, ...data1];

Array Clone :

const data1 = [1, 2, 3];
const data2 = test1.slice()
// Optimize
const data1 = [1, 2, 3];
const data2 = [...data1];

18、 String template

const test = 'hello ' + text1 + '.'
// Optimize
const test = `hello ${text}.` 

19、 Data deconstruction

const a1 = this.data.a1;
const a2 = this.data.a2;
const a3 = this.data.a3;
// Optimize
const { a1, a2, a3 } = this.data;

20、 Array to find a specific value

Arrays look for specific values by index , We can use logical bit operators Instead of judging .

“~” Operator ( Bit non ) Used to reverse a binary operands bit by bit
if(arr.indexOf(item) > -1)
// Optimize
if(~arr.indexOf(item))
// or
if(arr.includes(item))

21、Object.entries()

const data = { a1: 'abc', a2: 'cde', a3: 'efg' };
Object.entries(data);
/** Output :
[ [ 'a1', 'abc' ],
[ 'a2', 'cde' ],
[ 'a3', 'efg' ]
]
**/

22、Object.values()

We can go through Object.values() Convert the contents of an object to an array . as follows :

const data = { a1: 'abc', a2: 'cde' };
Object.values(data);
/** Output :
[ 'abc', 'cde']
**/

23、 Find the square

Math.pow(2,3);
// Optimize
2**3;

24、 Index abbreviation

for (var i = 0; i < 10000; i++)
// Optimize
for (var i = 0; i < 1e4; i++) {

25、 Object attribute shorthand

let key1 = '1';
let key2 = 'b';
let obj = {key1: key1, key2: key2};
// Abbreviation
let obj = {
key1,
key2
};

26、 String to number

let a1 = parseInt('100');
let a2 = parseFloat('10.1');
// Abbreviation
let a1 = +'100';
let a2 = +'10.1';


️ Welcome to quality company [ give the thumbs-up + Collection + Comment on ]</font>

I'm a fawn , Article synchronization update Github, You can also search it on wechat 「 Deer animation programming 」 The first time to receive article update notification , reply “ front end ” You can get the interview booklet compiled by fawn .
版权声明
本文为[fawn]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223094753391B.html

  1. How to build a high performance front end intelligent reasoning engine
  2. How to become a professional front end engineer in 2021?
  3. How to transform single / micro service application into serverless application
  4. How to transform single / micro service application into serverless application
  5. How to transform single / micro service application into serverless application
  6. How to connect the ground gas to the micro front end?
  7. How to connect the ground gas to the micro front end?
  8. How to connect the ground gas to the micro front end?
  9. Vue server rendering principle analysis and introduction
  10. Realize the correct loading of text message
  11. Building my own project scaffolding with yeoman
  12. JavaScript advanced prototype and prototype chain
  13. React background management front end system (based on open source framework development) start
  14. JS practical skills breakpoint debugging
  15. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  16. Get page element location
  17. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  18. Delayed code execution in flutter
  19. Reconfiguration experience of KOA middleware system
  20. Add comments to your blog
  21. Svg editor -- new path
  22. Detailed explanation of debounce and throttle of JavaScript function
  23. Anti shake and throttling and corresponding react hooks package
  24. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  25. Front end, school recruitment, Taobao, guide
  26. [vue2 & G6] get started quickly
  27. Canvas from the beginning to the pig
  28. Take five minutes to standardize the code comments?
  29. Some thoughts on sass
  30. what?! You haven't filled in the award information yet
  31. How to get the interface + tsdoc needed by TS through swagger
  32. Binary tree
  33. Canvas drawing method in Web screenshot
  34. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  35. Become a big influence of technology? Coding pages quickly build personal blog
  36. Object and array deconstruction, spread operator, rest operator
  37. Analysis of Axios source code
  38. Two ways to delete useless code in project (Practical)
  39. Edit your picture with canvas
  40. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone
  41. JS mechanism 3: stack, heap, garbage collection
  42. [grid compression evaluation] meshquan, meshopt, Draco
  43. Deep understanding of Vue modifier sync [Vue sync modifier example]
  44. WebView for front end engineers
  45. React form source code reading notes
  46. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  47. On the sequence of event capture and event bubbling
  48. Help you build a systematic understanding of the front end scaffolding
  49. commander.js Principle analysis
  50. Common usage of nginx
  51. H5 jump to wechat app
  52. Front end algorithm interview must brush questions series [14]
  53. Thinking of cross end practice
  54. Vue server rendering principle analysis and introduction
  55. [KT] vscode plug in development example series (2)
  56. Design ideas of react and Vue framework
  57. JavaScript String.prototype.replaceAll 兼容性导致的问题
  58. JavaScript String.prototype.replaceAll Problems caused by compatibility
  59. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  60. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%