Created
February 13, 2022 22:05
-
-
Save jasonleehodges/19a163ee79feb9053f01503aca44a63a to your computer and use it in GitHub Desktop.
Optional Chaining and Nullish Coalescing Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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