patternjavascriptModerate
Javascript condition optimization
Viewed 0 times
javascriptoptimizationcondition
Problem
Can the following condition be optimized/simplified ?
So basically if properties does not have a width or height property or the width or height property is less than or equal to zero then return
if (!this.properties.width ||
this.properties.width <= 0 ||
!this.properties.height ||
this.properties.height <= 0)
return;So basically if properties does not have a width or height property or the width or height property is less than or equal to zero then return
Solution
I'd simply flip it around:
This will catch
Update: There's one edge-case I've come across: Arrays. It's some unfortunate JavaScript weirdness to do with type coercion:
So an array with just a single numeric element will be treated as a number when comparing.
Well, actually, as far as I can tell, the array is coerced to a string by coercing each element to a string, and joining them with a comma, and the joined string is then compared lexicographically coerced to a number in order to be compared. (Thanks to Robert in the comments for the correction)
I love JavaScript, but sometimes... jeez...
if( !(this.properties.width > 0 && this.properties.height > 0) ) {
return;
}This will catch
null, undefined, NaN, etc., etc.. It will allow numeric strings (provided they can be coerced to a number greater than zero), and of course it'll allow straight-up positive, non-zero numbers.Update: There's one edge-case I've come across: Arrays. It's some unfortunate JavaScript weirdness to do with type coercion:
[] > 0; // => false (so far so good)
[0] > 0; // => false (as it should be)
[1] > 0; // => true (what?)
[1, 1] > 0; // => false (WHAT?)So an array with just a single numeric element will be treated as a number when comparing.
Well, actually, as far as I can tell, the array is coerced to a string by coercing each element to a string, and joining them with a comma, and the joined string is then compared lexicographically coerced to a number in order to be compared. (Thanks to Robert in the comments for the correction)
[1] + 0; // => "10"
[1, 1] + 0; // => "1,10"
"0" > 0; // => false
"1" > 0; // => true
"1,1" > 0; // => falseI love JavaScript, but sometimes... jeez...
Code Snippets
if( !(this.properties.width > 0 && this.properties.height > 0) ) {
return;
}[] > 0; // => false (so far so good)
[0] > 0; // => false (as it should be)
[1] > 0; // => true (what?)
[1, 1] > 0; // => false (WHAT?)[1] + 0; // => "10"
[1, 1] + 0; // => "1,10"
"0" > 0; // => false
"1" > 0; // => true
"1,1" > 0; // => falseContext
StackExchange Code Review Q#67432, answer score: 11
Revisions (0)
No revisions yet.