0

For example:

  data.forEach(element => {
    if (element) {
      this.myList.push({label: element.service.name, value: element.serviceId,
        service: element.service.name, typeOfService: element.typeOfService.name});
    }
  });

Is it a null check? Because in that case it's redundant here, right?

mal
  • 3,022
  • 5
  • 32
  • 62
  • Why would it be redundant? – Ivar Jul 25 '22 at 13:28
  • 1
    Nah you still would need to check because of maybe this array: [null, {}, null, {}] – Alexander Krum Jul 25 '22 at 13:29
  • 3
    "Because in that case it's redundant here, right?" — We can't tell if it is redundant. We don't know what the type of `data` is. e.g. It might be `SomeObject[]` or it might be `SomeObjectOrNull[]`. – Quentin Jul 25 '22 at 13:30
  • the if will check for a truthy value (a value that can be considered true) – phuzi Jul 25 '22 at 13:31
  • It checks if the element can be converted to a truthy value, preventing it from blowing up if the element is not there – alexandercannon Jul 25 '22 at 13:31
  • @Ivar I'm a java programmer, I'm not used to seeing null elements in a list. – mal Jul 25 '22 at 13:43
  • So if I want to add to this if statement, would this do the trick: `if(element !== null && (other conditions here) {} ` – mal Jul 25 '22 at 13:47
  • @mal Also in Java many collections (including many List implementations) can contain `null` values. As a matter of fact, when you create a non-primitive array in Java, by default all the values are `null`. – Ivar Jul 25 '22 at 13:50
  • 1
    As others have pointed out, `if (element)` is not necessarily the same as `if (element !== null)`. If you don't want to change the existing behavior, use `if (element && (other conditions))`. – Ivar Jul 25 '22 at 13:52

0 Answers0