Skip to content

Instantly share code, notes, and snippets.

@jasonleehodges
Created February 13, 2022 22:05
Show Gist options
  • Save jasonleehodges/19a163ee79feb9053f01503aca44a63a to your computer and use it in GitHub Desktop.
Save jasonleehodges/19a163ee79feb9053f01503aca44a63a to your computer and use it in GitHub Desktop.
Optional Chaining and Nullish Coalescing Examples
const myCharacter: Character = api.get<Character>(`/character/${characterId}`);
if(myCharacter.metadata.type === 'Hero') {
// this will blow up if there is no "metadata" property on the "myCharacter" object
// Cannot read property 'type' of undefined
}
if(myCharacter?.metadata?.type === 'Hero') {
// the optional chaining operator will default the entire expression to undefined
// if any property along the way is undefined. This condition will evaluate to false
// in that scenario since undefined !== 'Hero'
}
if(myCharacter?.metadata?.type ?? 'Hero' === 'Hero') {
// the combination of optional chaining and nullish coalescer here will ensure that
// if any property is undefined then it will default the expression to 'Hero' thus
// making the condition evaluate to true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment