Home>Article>Web Front-end> 4 Tips for Writing Short and Concise JS Code (Share)
How to make the JS code written shorter? The following article will share with you 4 tips for writing short and concise JS code. I hope it will be helpful to you!
The logical operatorsand (&&)
in Javascript can produce a short circuit, for example
console.log(true && 0 && 2); // 0 console.log(true && 'test' && 2) // 2
That is, the code goes from left to right. If it encountersundefined
,null
,0
, etc., it will be converted intofalse# When the value of ## is reached, the operation will no longer continue.
x == 0 && foo() // 等价于 if( x == 0 ){ foo() }
const student = { name : { firstName : 'Joe' } }We want to do something if firstname exists, we must not Without checking layer by layer
if(student && student.name && student.name.firstName){ console.log('student First name exists') }The chain judgment operator will stop and return undefined when a value cannot be obtained at a certain layer
if(student?.name?.firstName){ console.log('student First name exists') }
if...else...or return a default value
const foo = () => { return student.name?.firstName ? student.name.firstName : 'firstName do not exist' } console.log(foo())This situation , we can further simplify the code by null value merging
const foo = () => { return student.name?.firstName ?? 'firstName do not exist' } console.log(foo())is much like the or
||operator, but
??only works for
undefinedand
nullworks, you can avoid the trouble of 0 values
const foo = () => { if(x<1) { return 'x is less than 1' } else { if(x > 1){ return 'x is greater than 1' } else { return 'x is equal to 1' } } }By deleting The else condition can make if else nesting less complicated, because the return statement will stop the code execution and return the function
const foo = () => { if(x<1){ return 'less than 1' } if(x>1){ return 'x is greater than 1' } return 'x is equal to 1' }
Good code does not necessarily need to be as short as possible, sometimes it is too concise The code will make the debugging process more troublesome, so readability is the most important, especially when multiple people collaborate.For more programming-related knowledge, please visit:
Introduction to Programming! !
The above is the detailed content of 4 Tips for Writing Short and Concise JS Code (Share). For more information, please follow other related articles on the PHP Chinese website!