0
if (valid === null) {
  return '';
} else if (!valid) {
  return 'is-not-valid';
} else if (valid) {
  return 'is-valid';
} else {
  return '';
}

I have the above if-else-if chain in the code, trying to see if I can write the same logic in one or two lines.

2

2 Answers 2

3

Since you want to distinguish between three types of values, you have to make at least two checks already. The else case will never be hit since either !valid or valid will be true. That also means you can reduce the last else if to an else:

if (valid === null) {
  return '';
} else if (!valid) {
  return 'is-not-valid';
} else {
  return 'is-valid';
}

But you could condense this logic using the conditional operator:

return valid === null ? '' : (valid ? 'is-valid' : 'is-not-valid');
Sign up to request clarification or add additional context in comments.

Comments

1

Although I think your example (sans the redundant else block) looks pretty good, you can write it on one line like this:

return valid === null ? '' : (valid ? 'is-valid' : 'is-not-valid')

I prefer the original though

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.