Use the Optional Chaining Operator to Simplify Checking for Nullish Values

Sam Selikoff
InstructorSam Selikoff
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

The Optional Chaining Operator, ?., can be used as a simple way to check if a variable has a nullish value (null or undefined). Instead of littering your app with checks like data && data.movies, you can write data?.movies instead.

Check out the Optional chaining MDN docs to read more about the new operator.

Sam Selikoff: [0:00] This app renders a list of movies after fetching the data from an API endpoint. If I reload the app, you will see that it first renders without the data, and then re-renders once the data is coming back.

[0:11] Since it needs to be able to render before the data has come back, we have this check to make sure that there is data before we try to map over the movies key.

[0:20] If we were to remove this check, we'll get an error that React is trying to read property movies of null. Adding a check like data && data.movies is a common way to solve this problem.

[0:33] We're making sure the data variable isn't null or undefined before trying to call that movies on it. The optional chaining feature is a new syntax that lets us do the same thing. Instead of having to check whether data is undefined on its own, we can do it like this ?.

[0:51] This ?. is the syntax for optional chaining. It essentially acts like a short circuit for anything to the left of it. It means if the thing to the left isn't null or undefined, go ahead and continue with the statement. If it is, just return undefined.

[1:09] Here when we save this and look at our app, we can see that the initial render doesn't have any data but it doesn't throw that error. Once the data comes back, we're able to map over the rest of the movies and render out the full table.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today