JS 4 Super Practical Tips to Improve Development Efficiency
- 2021-11-23 22:14:48
- OfStack
1. Short circuit judgment
You can use this method when you only need a simple if condition
let x = 0;
let foo = () => console.log(' Executed ');
if(x === 0){
foo()
}
By using
&&
Operator to implement the same if functionality, if
&
&
The previous condition is
false
, then
&
&
The subsequent code will not be executed.
let x = 0;
let foo = () => console.log(' Executed ');
x === 0 && foo()
You can also add more if conditions, but this will also increase the complexity of the statement, and more than 2 conditions are not recommended.
let x = 0;
let y = 0;
let foo = () => console.log(' Executed ');
x === 0 && y === 0 && foo()
2. Optional chain operator (? )
We often determine whether there is a certain one in the JS object
key
Because it is sometimes uncertain whether the data returned by the background API is correct.
user
Object contains 1 property
name
Object of,
name
Object has 1 property
firstName
, using
user.name.firstName
If the judgment is made directly, an error will be reported if the name attribute does not exist, so it is necessary to judge whether user. name exists before judgment, and two layers of if judgment need to be nested.
let user = {
name : {
firstName : ' Aofukuisi '
}
}
if(user.name){
if(user.name.firstName){
console.log('user Object Include firstName Field ')
}
}
We can use it at this time? Operator to simplify the operation, if
user.name
Does not exist, will also return
false
Therefore, the 1-layer judgment is directly used
let user = {
name : {
firstName : ' Aofukuisi '
}
}
if(user.name?.firstName){
console.log('user Object Include firstName Field ')
}
3. Null value merge operator (? ? )
Compared with if/else, the 3-yuan operator is shorter. If the logic is simple, it is very convenient to use.
For example:
let user = {
name : {
firstName : ' Aofukuisi '
}
}
let foo = () => {
return user.name?.firstName ?
user.name.firstName :
'firstName Nonexistent '
}
console.log(foo())
First use? Operator to interpret whether it exists, if it exists, it will return, if it does not exist, it will return false, and enter the following logic
Use? ? Arithmetic makes the code simpler
let user = {
name : {
firstName : ' Aofukuisi '
}
}
let foo = () => {
return user.name?.firstName ??
'firstName Nonexistent '
}
console.log(foo())
4. return termination function
The following function determines the value of x, using a large number of
false
0
Nesting
let x = 1;
let foo = () => {
if(x < 1){
return 'x Less than 1'
} else {
if(x > 1){
return 'x Greater than 1'
}else{
return 'x Equal to 1'
}
}
}
console.log(foo())
This
false
0
Nesting can be deleted
else
Condition to simplify the code, because
return
Statement terminates code execution and returns the function.
let x = 1;
let foo = () => {
if(x < 1){
return 'x Less than 1'
}
if(x > 1){
return 'x Greater than '
}
return 'x Equal to 1'
}
console.log(foo())