Home > Web Front-end > JS Tutorial > 18 JavaScript Optimization Tips You Need to Know

18 JavaScript Optimization Tips You Need to Know

WBOY
Release: 2021-12-14 18:49:36
forward
1731 people have browsed it

In this article, let’s take a look at 18 optimization techniques for JavaScript. It is suitable for all developers who are using JavaScript programming. The purpose of this article is to help you become more proficient in using the JavaScript language for development work. I hope it will be useful to everyone. help.

18 JavaScript Optimization Tips You Need to Know

1. Judgment of multiple conditions

When we need to judge multiple values , we can use the includes method of the array.

//Bad
if (x === 'iphoneX' || x === 'iphone11' || x === 'iphone12') {
//code... 
}
//Good
if (['iphoneX', 'iphone11', 'iphone12'].includes(x)) {
//code...
}
Copy after login

2. If true ... else

When the inside of the if-else condition does not contain greater logic, the ternary operator will be better.

// Bad
let test= boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Good
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
Copy after login

After nesting the conditions, we retain the content as shown below (three eyes of complex points):

let x = 300,
let test2 = (x > 100) ? &#39;greater 100&#39; : (x < 50) ? &#39;less 50&#39; : &#39;between 50 and 100&#39;;
console.log(test2); // "greater than 100"
Copy after login

3. Null, Undefined, '' null value Check

Sometimes we need to check whether the variable we reference for the value is not null or Undefined or '', we can use the short-circuit writing

// Bad
if (first !== null || first !== undefined || first !== &#39;&#39;) {
let second = first;
}
// Good 短路写法
let second = first|| &#39;&#39;;
Copy after login

4. Null value check and assign default value

When we assign a value and find that the variable is empty and need to assign a default value, we can use the following short-circuit writing method

let first = null,
let second = first || &#39;default&#39;
console.log(second)
Copy after login

4. Double-bit operators

Bit operators are the basic knowledge points in JavaScript beginner tutorials, but we don’t often use bit operators. Because no one wants to work with 1s and 0s without dealing with binary.

But the double-bit operator has a very practical case. You can use double-bit operators instead of Math.floor( ). The advantage of the double negative bit operator is that it performs the same operation faster

// Bad
Math.floor(4.9) === 4  //true
// Good
~~4.9 === 4  //true
Copy after login

5. ES6 common small optimizations - Object properties

const x,y = 5
// Bad
const obj = { x:x, y:y }
// Good
const obj = { x, y }
Copy after login

6. ES6 common minor optimizations - arrow functions

//Bad
function sayHello(name) {
  console.log(&#39;Hello&#39;, name);
}
setTimeout(function() {
  console.log(&#39;Loaded&#39;)
}, 2000)
list.forEach(function(item) {
  console.log(item)
})
// Good
const sayHello = name => console.log(&#39;Hello&#39;, name)
setTimeout(() => console.log(&#39;Loaded&#39;), 2000)
list.forEach(item => console.log(item))
Copy after login

7. ES6 common minor optimizations - implicit return values

Return value is the keyword we usually use to return the final result of the function. An arrow function with only one statement can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).

To return a multi-line statement (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

//Bad
function calcCircumference(diameter) {
  return Math.PI * diameter
}
// Good
const calcCircumference = diameter => (
  Math.PI * diameter
)
Copy after login

8. ES6 common minor optimizations - destructuring assignment

const form = { a:1, b:2, c:3 }
//Bad
const a = form.a
const b = form.b
const c = form.c
// Good
const { a, b, c } = form
Copy after login

9. ES6 common minor optimizations - expansion operations The symbol

The return value is the keyword we usually use to return the final result of the function. An arrow function with only one statement can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).

To return a multi-line statement (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

const odd = [ 1, 3, 5 ]
const arr = [ 1, 2, 3, 4 ]
// Bad
const nums = [ 2, 4, 6 ].concat(odd)
const arr2 = arr.slice( )
// Good
const nums = [2 ,4 , 6, ...odd]
const arr2 = [...arr]
Copy after login

10. Common array processing

Master the common methods of arrays and keep them in your mind. Don’t look at the API when writing. This can effectively improve coding efficiency. After all, these methods are used every day

every some filter map forEach find findIndex reduce includes

const arr = [1,2,3]
//every 每一项都成立,才会返回true
console.log( arr.every(it => it>0 ) ) //true
//some 有一项都成了,就会返回true
console.log( arr.some(it => it>2 ) ) //true
//filter 过滤器
console.log( arr.filter(it => it===2 ) ) //[2]
//map 返回一个新数组
console.log( arr.map(it => it==={id:it} ) ) //[ {id:1},{id:2},{id:3} ]
//forEach 没有返回值
console.log( arr.forEach(it => it===console.log(it)) ) //undefined
//find 查找对应值 找到就立马返回符合要求的新数组
console.log( arr.find(it => it===it>2) ) //3
//findIndex 查找对应值 找到就立马返回符合要求新数组的下标
console.log( arr.findIndex(it => it===it>2) ) //2
//reduce 求和或者合并数组
console.log( arr.reduce((prev,cur) => prev+cur) ) //6
//includes 求和或者合并数组
console.log( arr.includes(1) ) //true
//数组去重
const arr1 = [1,2,3,3]
const removeRepeat = (arr) => [...new Set(arr1)]//[1,2,3]
//数组求最大值
Math.max(...arr)//3
Math.min(...arr)//1
//对象解构 这种情况也可以使用Object.assign代替
let defaultParams={
    pageSize:1,
    sort:1
}
//goods1
let reqParams={
    ...defaultParams,
    sort:2
}
//goods2
Object.assign( defaultParams, {sort:2} )
Copy after login

11. Comparison returns

Using comparison in the return statement can reduce the code from 5 lines to 1 line.

// Bad
let test
const checkReturn = () => {
    if (test !== undefined) {
        return test;
    } else {
        return callMe(&#39;test&#39;);
}
}
// Good
const checkReturn = () => {
return test || callMe(&#39;test&#39;);
}
Copy after login

12. Short function call

We can use the ternary operator to implement this type of function.

const test1 =() => {
  console.log(&#39;test1&#39;);
}
const test2 =() => {
  console.log(&#39;test2&#39;);
}
const test3 = 1;
if (test3 == 1) {
  test1()
} else {
  test2()
}
// Good
test3 === 1? test1():test2()
Copy after login

13.switch code block (ifelse code block) abbreviation

We can save the condition in the key-value object, and then Use according to conditions.

// Bad
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Good
const data = {
  1: test1,
  2: test2,
  3: test
}
data[anything] && data[anything]()
// Bad
if (type === &#39;test1&#39;) {
  test1();
}
else if (type === &#39;test2&#39;) {
  test2();
}
else if (type === &#39;test3&#39;) {
  test3();
}
else if (type === &#39;test4&#39;) {
  test4();
} else {
  throw new Error(&#39;Invalid value &#39; + type);
}
// Good
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
const func = types[type];
(!func) && throw new Error(&#39;Invalid value &#39; + type); func();
Copy after login

14. Multi-line string abbreviation

When we process multi-line strings in code, we can do this:

// Bad
const data = &#39;abc abc abc abc abc abc\n\t&#39;
+ &#39;test test,test test test test\n\t&#39;
// Good
const data = `abc abc abc abc abc abc
         test test,test test test test`
Copy after login

15. Object.entries() Object.values() Object.keys()

Object.entries() This feature can Object is converted into an array of objects.

Object.values() can get the object value

Object.keys() can get the object key value

const data = { test1: &#39;abc&#39;, test2: &#39;cde&#39; }
const arr1 = Object.entries(data)
const arr2 = Object.values(data)
const arr3 = Object.keys(data)
/** arr1 Output:
[ 
    [ &#39;test1&#39;, &#39;abc&#39; ],
    [ &#39;test2&#39;, &#39;cde&#39; ],
]
**/
/** arr2 Output:
[&#39;abc&#39;, &#39;cde&#39;]
**/
/** arr3 Output:
[&#39;test1&#39;, &#39;test2&#39;]
**/
Copy after login

16. More Repeat a string

In order to repeat the same character multiple times, we can use a for loop and add them to the same loop. How to abbreviate it?

//Bad 
let test = &#39;&#39;; 
for(let i = 0; i < 5; i ++) { 
  test += &#39;test,&#39;; 
} 
console.log(str);// test,test,test,test,test,
//good 
console.log(&#39;test,&#39;.repeat(5))
Copy after login

17. The abbreviation of power

The good of mathematical exponential power function is as follows:

//Bad 
Math.pow(2,3)// 8
//good 
2**3 // 8
Copy after login

18. Number separators

#You can now easily separate numbers by just using _. This will make it easier to handle large amounts of data.

//old syntax
let number = 98234567
//new syntax
let number = 98_234_567
Copy after login

If you want to use the latest features of the latest version of JavaScript (ES2021/ES12), please check the following:

  • 1.replaceAll(): Returns a new string in which all matching patterns are replaced by new replacement words.

  • 2.Promise.any(): An iterable Promise object is required. When a Promise is completed, a Promise with a value is returned.

  • 3.weakref: This object holds a weak reference to another object and does not prevent the object from being garbage collected.

  • 4.FinalizationRegistry: Allows you to request a callback when the object is garbage collected.

  • 5. Private methods: Modifiers for methods and accessors: Private methods can be declared with #.

  • 6. Logical operators: && and || operators.

  • 7.Intl.ListFormat: This object enables language-sensitive list formatting.

  • 8.Intl.DateTimeFormat: This object enables language-sensitive date and time formatting.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of 18 JavaScript Optimization Tips You Need to Know. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template