Optional properties with JavaScript

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!

Published by _adam

WordPress developer by day, night, weekends, holidays, etc. I mainly stick to the back-end code where I feel it's the most glamorous.

Leave a comment

Your email address will not be published. Required fields are marked *