Created
July 11, 2024 02:37
-
-
Save kevboutin/dc2181b26e5555874b9b2a84238a692b to your computer and use it in GitHub Desktop.
Streamlined operator example
This file contains hidden or 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
/* The streamlined operator (“ ?. ”) acts as a nullish coalescing operator. It checks if | |
* the preceding value is “ null ”or “ undefined ” before attempting to access the next | |
* property. This simplifies conditional checks and streamlines your code, making it more | |
* readable and less error-prone. | |
*/ | |
async function getUser(userId) { | |
const user = await db.getUser(userId); | |
// Traditional approach (prone to errors with undefined values) | |
if (user && user.profile && user.profile.avatarUrl) { | |
return user.profile.avatarUrl; | |
} else { | |
return null; | |
} | |
// Approach using the streamlined operator | |
return user?.profile?.avatarUrl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment