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.
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... }
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;
After nesting the conditions, we retain the content as shown below (three eyes of complex points):
let x = 300, let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100'; console.log(test2); // "greater than 100"
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 !== '') { let second = first; } // Good 短路写法 let second = first|| '';
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 || 'default' console.log(second)
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
5. ES6 common small optimizations - Object properties
const x,y = 5 // Bad const obj = { x:x, y:y } // Good const obj = { x, y }
6. ES6 common minor optimizations - arrow functions
//Bad function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000) list.forEach(function(item) { console.log(item) }) // Good const sayHello = name => console.log('Hello', name) setTimeout(() => console.log('Loaded'), 2000) list.forEach(item => console.log(item))
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 )
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
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]
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} )
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('test'); } } // Good const checkReturn = () => { return test || callMe('test'); }
12. Short function call
We can use the ternary operator to implement this type of function.
const test1 =() => { console.log('test1'); } const test2 =() => { console.log('test2'); } const test3 = 1; if (test3 == 1) { test1() } else { test2() } // Good test3 === 1? test1():test2()
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 === 'test1') { test1(); } else if (type === 'test2') { test2(); } else if (type === 'test3') { test3(); } else if (type === 'test4') { test4(); } else { throw new Error('Invalid value ' + type); } // Good const types = { test1: test1, test2: test2, test3: test3, test4: test4 }; const func = types[type]; (!func) && throw new Error('Invalid value ' + type); func();
14. Multi-line string abbreviation
When we process multi-line strings in code, we can do this:
// Bad const data = 'abc abc abc abc abc abc\n\t' + 'test test,test test test test\n\t' // Good const data = `abc abc abc abc abc abc test test,test test test test`
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: 'abc', test2: 'cde' } const arr1 = Object.entries(data) const arr2 = Object.values(data) const arr3 = Object.keys(data) /** arr1 Output: [ [ 'test1', 'abc' ], [ 'test2', 'cde' ], ] **/ /** arr2 Output: ['abc', 'cde'] **/ /** arr3 Output: ['test1', 'test2'] **/
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 = ''; for(let i = 0; i < 5; i ++) { test += 'test,'; } console.log(str);// test,test,test,test,test, //good console.log('test,'.repeat(5))
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
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
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!