How to simplify my conditional statement?

I am trying to simplify the following codes. Codes seem to me superfluous. Can anyone help me out? Thank you very much!

if(area.regionCode=='0' || area.regionCode==null){ var fakecode=area.region.substring(0, area.region.length - 1); area.region= fakecode +i; } 
+4
source share
3 answers

Whenever you think that some code is not displayed directly, try to give it a new house with a suitable name:

 if (!isValidRegionCode(area.regionCode)) { ... } ... function isValidRegionCode(regionCode) { return area.regionCode != null && area.regionCode != '0'; } 

It contains more code in general, but makes your intentions clear.

+2
source

I would recommend explicit conditional checks. Using:

 if (area.regionCode) { } 

A style of logic, one treats varAny as a boolean. Therefore, JavaScript will perform an implicit conversion to the boolean of any type of varAny object.

or

  if(Boolean(area.regionCode)){ codes here; } 

both will work the same

returns false for the next one

  • Null
  • undefined
  • 0
  • ""
  • Lying.

beware returns true for the null string "0" and the space "".

you can also trim the output first, so the problem " " will be solved here tutorial How to crop a string in javascript?

in the case described by @mttrb and @nnnnnn you can first convert the string to int or float to parseInt() and parseFloat() check this Convert strings to numbers

0
source
 if(parseInt(area.regionCode) > 0) {} 
0
source

Source: https://habr.com/ru/post/1434741/


All Articles