0

I would like to simplify this expression but don't know how. There has to be a way to have the same expression without the three conditions.

if ( request.Document != null &&
      request.Document != undefined &&
      request.Document != "" )

Just for context I am talking something similar to c#'s !string.isNullOrEmpty()

MatejDodevski
  • 187
  • 13
  • As a a value other than any of those outline is considered truthy when coerced in JS, you can just use `if (request.Document) { ...` – Rory McCrossan Sep 23 '22 at 09:17
  • What will happen if the string is empty ("")? @RoryMcCrossan – MatejDodevski Sep 23 '22 at 09:18
  • @MatejDodevski try it, you'll see – Layhout Sep 23 '22 at 09:19
  • `x != undefined` <-- Don't do this; you should use `typeof x === 'undefined'` instead. – Dai Sep 23 '22 at 09:19
  • you can simply write ```if ( request.Document ) { ..... }``` This will return false for empty string, undefined, null and 0 as number – Srushti Shah Sep 23 '22 at 09:19
  • 1
    @MatejDodevski an empty string is falsy. – Rory McCrossan Sep 23 '22 at 09:19
  • @MatejDodevski you may consider `if(request.Document?.trim())` as in `isNullOrWhitespace()`. Besides that, you should get familiar with [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values in JS. – Thomas Sep 23 '22 at 09:24

1 Answers1

1
if (request.Document) {
  ...
}

as null, undefined, '' will all return false.

(but [], {} or ' ' will return true)

Check the equality table for more info about other values.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • _"but `[]`, `{}` or `' '` will return `true`"_ - right, so to handle those cases methinks it would be sensible to use `if( ( typeof request.Document === 'string' ) && /^\w+$/.test( request.Document ) ) { ... }` (assuming that regex is okay). – Dai Sep 23 '22 at 09:29