JavaScript has been around for ages and as a backend developer I have usually left it alone to let the “Front-Enders” to deal with unless absolutely necessary. That’s not to say I haven’t written my fair share of JS over the years, after all I’ve been dealing with it in one form or another since you were required to specify the JS version in the tag all the way back to version 1.2 and jQuery wasn’t a thing.
Since I have started dabbling more and more with custom Gutenberg Blocks it seems as though I am learning something new everyday. One of the cool things I have learn recently is optional properties. Although this may not be the actual term used to describe the functionality it is still cool.
Say you have the following object in it’s ideal state (abbreviated for clarity):
const postObject = {
...
title: {
rendered: "My Title",
...
},
...
}
In order to access the rendered title you simple call:
postObject.title.rendered
Easy enough, but what if your object is not in the ideal state, what if it’s empty? Not a problem! Javascript makes this super easy. Instead of having to check hasOwnProperty
a bunch of times you can simply use the optional property checking using ?
and be on your way:
postObject?.title?.rendered
Here is a more practical example using JSX (because Gutenberg and React and it is much clearer):
return (
<p>{ ( postObject?.title?.rendered && postObject.title.rendered ) || '' }</p>
);
This will either output the rendered title or an empty string if either title
or title.rendered
are not found in your postObject
object.
This makes your code much cleaner and as a result easier to read. As a Backend dev I really wish PHP made it this easy without throwing a pile of notices, warnings, or errors at you, like empty($post_object->title->rendered
) does.
Yes, I know data integrity could also solve the problem by ensuring the data was always formatted correctly so you don’t need to worry about it but it is not always possible, especially when working with 3rd-party REST API’s.
I know it’s nothing special, just something I thought was neat. I hope you were able to learn something from this. I linked the MSDN documentation above if you want to know more!
Update
PHP 8.0 introduced the null-safe operator which offers functionality very similar to Javascript in that you can now do things like:
echo $my_object?->maybe_a_property || 'something';
This is just a quick example, I recommend reading the linked article for more details and learn the rest of what this functionality can do.
Keep in mind, this only works if the property (or method) would return null, this does not replace an empty check, see this example:
...rest of the code building $my_object...
$my_object->maybe_a_property = '';
$my_var = $my_object?->maybe_a_property || 'something';
var_dump( $my_var );
Output:
string(0) ""
However
$my_object->maybe_a_property = null;
$my_var = $my_object?->maybe_a_property || 'something';
var_dump( $my_var );
Output:
string(9) "something"