0

I was looking at these if statements:

 if (cellDate < filterLocalDateAtMidnight) {
    return -1;
 } else if (cellDate > filterLocalDateAtMidnight) {
    return 1;
 } else {
    return 0;
 }

from this article and I was wondering why short hand if statements were not used (I.e. using the ternary operator)> is there a disadvantage to using it? It seems like a good opportunity to use it.

If it can be used, is the below how you would simplify it? I'd like to refactor my code although I'm a little worried about straying from the example in the article (and inadvertently introducing some special case glitches)

cellDate < filterLocalDateAtMidnight ? -1 :(cellDate > filterLocalDateAtMidnight : 1 : 0 );

i assume the separate if statements are used in case of null/undefined values?

1
  • Your ternary expression correctly represents the if else statements. If else statements can be expressed in a compact way using ternary operator. Commented Jul 23, 2017 at 12:07

1 Answer 1

1

Nested ternaries are confusing to read and should generally avoided. See the Airbnb style guide.

With numerical comparisons you can usually just use subtraction. i.e.

return cellDate - filterLocalDateAtMidnight;

But beware that this solution is vulnerable to integer overflow for really large numbers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.