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、Null
、Undefined
、''
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 .