const book = {
title:"My Favorite JS Functions",
author:{
firstName:"John",
lastName:"Doe"
}
}
// (1)
book.author.firstName
// (2)
const authorName = book.author && book.author.firstName
? book.author.firstName
: 'Unknown'
// (3)
const authorName = book.author !== undefined
&& book.author.firstName !== undefined
? book.author.firstName
: 'Unknown'
// (Chaining)
const authorName = book?.author?.firstName !== undefined
? book.author.firstName
: 'Unknown'
// (Chaining and Nullish Coalescing)
const authorName = book?.author?.firstName ?? 'Unknown'
Created
April 20, 2023 15:53
-
-
Save xgracias/69e504384fc4e10c45217b4b2fe62f3e to your computer and use it in GitHub Desktop.
80% Cleaner JavaScript Code Using Optional Chaining and Nullish Coalescing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment