PHP is constantly evolving and brings new features that help to write things better. One of my favorites is the null safe operator.
The null safe operator has been available for some time already - introduced in PHP 8.0. It is a really good feature to make code way shorter. So usually you write something like this:
$node = $this->entityTypeManager->getStorage('node')->load($nid);
$media_title = 'undefined';
if ($node !== NULL) {
$media = $node->get('field_media')->entity;
if ($media !== NULL) {
$media_title = $media->label();
}
}
In Drupal it's repetitive, there are a lot of objects that you need to load and check if they exist (someone may delete the referenced entity, but Drupal does not remove that reference from the field).
So instead of that, the sorter version would be something like this:
$node = $this->entityTypeManager->getStorage('node')->load($nid);
$media = $node?->get('field_media')->entity;
$media_title = $media?->label() ?? 'undefined';
It will break the chaining and return null, of the object before in null. So it is a really useful feature to know about and use.
If you write Javascript code, then there is the same thing available as well and it works with all the latest supported browsers. You need to add a question mark (?) before the dot and if the object is not defined, it will return a null value.
let name = jsonData?.tree[0]?.name ?? 'undefined';
In conclusion, the null safe operators are good for reducing code complexity and things look easier to understand. Languages are always evolving and these small features can help a lot.