Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created July 11, 2024 02:37
Show Gist options
  • Save kevboutin/dc2181b26e5555874b9b2a84238a692b to your computer and use it in GitHub Desktop.
Save kevboutin/dc2181b26e5555874b9b2a84238a692b to your computer and use it in GitHub Desktop.
Streamlined operator example
/* 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