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' } }
if(student && student.name && student.name.firstName){ console.log('student First name exists') }
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())
const foo = () => { return student.name?.firstName ?? 'firstName do not exist' } console.log(foo())
||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' } } }
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!