Mary Knize

Optional chaining and nullish coalescing in JavaScript

1 min read


Thanks to Internet Explorer, I'm slow to pick up on some of the newer JavaScript techniques that don't work on that old browser. Two of those techniques are optional chaining and the nullish coalescing operator, and today, I was able to clean up some code with those two techniques.

I'm working with some complex state in React, in particular state that changes depending on if a new file has been uploaded or not. If there's a file uploaded, we want to display the file's name. If not, we want to give the label an empty string.

My original code looked like this:

    label = { && ? : ''}
/> is set when the parent component is mounted, but audio_file may or may not be set depending on the data passed in. If there was no check for the existence of audio_file, the component would throw an error.

Thanks to optional chaining, I can simplify the statement a bit, by putting the ?. operator between audio_file and name. That way, if audio_file is null or undefined, it won't go looking for name.

    label = { ? : ''}

This is better, but I can clean up my code even more by using the nullish coalescing operator. Since audio_file?.name could equal null, I can use ?? to say, "If the left side of the statement is null or undefined, return the right side. Else, return the left side."

    label = { ?? ''}

Now I have a much shorter expression that does that same thing as the original, but is much less verbose.

Canonical URL