Reputation: 4239
I am trying to simplify the following codes. The codes seem to redundant to me. Are there anyone here can help me out? Thanks a lot!
if(area.regionCode=='0' || area.regionCode==null){
var fakecode=area.region.substring(0, area.region.length - 1);
area.region= fakecode +i;
}
Upvotes: 4
Views: 171
Reputation: 56467
Whenever you think some code is not directly revealing, try giving it a new home with a suitable name:
if (!isValidRegionCode(area.regionCode)) {
...
}
...
function isValidRegionCode(regionCode) {
return area.regionCode != null && area.regionCode != '0';
}
It has more code overall, but makes your intentions clear.
Upvotes: 2
Reputation: 57312
I would recommend explicit condition checks. When using:
if (area.regionCode) { }
Style of logic, one is treating varAny as a boolean value. Therefore, JavaScript will perform an implicit conversion to a boolean value of whatever object type varAny is.
or
if(Boolean(area.regionCode)){
codes here;
}
both will work same
returns false for the following,
beware returns true for string zero "0" and whitespace " ".
you can also first trim the output so " "
issue will be solve
here tutorial How do I trim a string in javascript?
in the @mttrb and @nnnnnn described case you can first convert string to either int or float by parseInt()
and parseFloat()
check this Converting strings to numbers
Upvotes: 0