Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Hi everyone, I’m Lonely and I’ve been cleaning up some minor optimizations in code review (sometimes the code is real) ~~
Null, Undefined, Null check
If a variable is null, if a variable is undefined, if a variable is null, if a variable is undefined, if a variable is null, if a variable is null, if a variable is undefined, if a variable is null.
Common writing:
if(username1 ! = =null|| username1 ! = =undefined|| username1 ! = =' ') {
let username = username1;
}
Copy the code
After the optimization: let the username = with username1 is | | ‘.
(This is also used when assigning default values to variables.)
There are multiple conditions for judging
The way we often use it is:
if (x === 'png' || x === 'jpeg' || x === 'jpg' || x === 'gif') {
/ / the next step
}
Copy the code
A simpler way is to store the values in an array using the includes method:
if (['png'.'jpeg'.'jpg'.'gif'].includes(x)) {
/ / the next step
}
Copy the code
If else optimization
It’s common to see if else nesting
if(val < 0) {}else if(val > 10) {}else( val > 100 ){}Copy the code
If else we can use the ternary operator to optimize if else when the logic inside is small:
let value = val < 0? 'aaa':( val > 10)? 'bbb':'ccc;
The for loop
Common is the common way to write a for loop: for (let I = 0; i < arr.length; i++)
Optimization is written for in or for of: for (let I in arr.length) or for (let I of arr.length)
The switch of the abbreviations
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
}
Copy the code
Optimally: Save the condition in a key-value object that can then be used based on the condition.
var data = {
1: test1,
2: test2,
3: test};
data[anything] && data[anything]();
Copy the code
An object is converted to an array of objects
Object.entries() converts an Object to an array of objects
const data = { a: '111'.b: '222'.c: '333' };
const arr = Object.entries(data);
console.log(arr);
Copy the code
Shorthand for powers
// Common method
Math.pow(2.3); / / 8
// The shorthand method
2**3 / / 8
Copy the code