1

I am creating same if else function on my program. And I want to make it more short but same logic.

if(!checkStringInput("Test", 14)){
     elementHasError($element);
} else {
     elementIsOk($element);
}

I am thinking this boolean condition can be a shorter one to:

CONDITION ? FUNCTION1; : FUNCTION2;

Thanks for the help!

2
  • Why make it shorter when the code gets less readable (maintainable)? Commented Dec 20, 2013 at 5:33
  • @edHeal - Sorry for that. But that whole code is always using. For me, it is a bit messy and I want something more short if calling it 10 times on my code. Commented Dec 20, 2013 at 5:48

4 Answers 4

3

Have you tried this

!checkStringInput("Test", 14)) ? elementHasError($element) : elementIsOk($element);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I am doing the wrong way on using this logic. I have ';' on both functions. Thank you for this information. Now it works.
Glad to help even if it some small ;)
3

Probably the shortest possible:

(checkStringInput("Test", 14) ? elementIsOk : elementHasError)($element);

4 Comments

Well, you could omit a few whitespaces :-) Actually this even looks clean, +1!
I like this approach but it may cause issues when the handler needs to be called in some context. For example: (checkStringInput("Test", 14) ? this.elementIsOk : this.elementHasError)($element); Well in this case, conetxt gets lost. OP can use this as well because he does not need any context in the method.
@blunderboy (checkStringInput("Test", 14) ? elementIsOk : elementHasError).call(this, $element);
@Purrfection I know there are more alternatives to this (like bind). I just wanted to make a point to the readers. Thanks anyway :)
0
!checkStringInput("Test", 14)? elementHasError($element): elementIsOk($element);

Comments

0

You seemed to have it correct. Were you looking for something else beyond the terniary operation?

!checkStringInput('Test', 14) ? elementHasError($element) : elementIsOk($element);

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.