Skip to content
Advertisement

checking for null in javascript

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.

Advertisement

Answer

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');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement