-2

I'm working on an Angular 11 project and I'm struggling with checking for null and undefined.

I have three strings - equipmentId, roomId and personnelId and a flag (boolean) adresseeChosen.

I want the adresseeChosen to be true if at least one of the above strings is not null / undefined, this is my code

this.adresseeChosen= (this.equipmentId != null && this.equipmentId != undefined)  
                      || (this.roomId != null && this.roomId != undefined) 
                      || (this.personnelId != null && this.personnelId != undefined) 

What's the short way of writing this? Thanks!

  • `(this.equipmentId != null || this.roomId != null || this.personnelId != null)` – VLAZ Feb 20 '21 at 09:02
  • Also relevant: [Checking for null or undefined](https://stackoverflow.com/q/38648087) | [How can I determine if a variable is 'undefined' or 'null'?](https://stackoverflow.com/q/2647867) | [JavaScript checking for null vs. undefined and difference between == and ===](https://stackoverflow.com/q/5101948) | [What is the difference between null and undefined in JavaScript?](https://stackoverflow.com/q/5076944) – VLAZ Feb 20 '21 at 09:03
  • @VLAZ I got that, but I'm looking for a even shorter approach ;) – Vasile Verssachen Feb 20 '21 at 09:06
  • Write a function to do the check? There isn't really a "shorter" way to check if three things satisfy some condition other than testing each of the three things. I don't know what you expect us to give you. Any code that will mean "check if x, y, or z are not null" still has to name the three of them. Your other alternative is to minify your code to save out a few bytes. It's still going to use the same operations but might you'd get about 6 characters less. – VLAZ Feb 20 '21 at 09:11

1 Answers1

0

You can write an utility function to check value is null or undefined. For example:

export function isNullUndefined(value): boolean {
  return (value === null) || (value === undefined);
}
Saghi Shiri
  • 314
  • 1
  • 15