Skip to content

Instantly share code, notes, and snippets.

@bullishgopher
Created April 20, 2023 15:53
Show Gist options
  • Save bullishgopher/69e504384fc4e10c45217b4b2fe62f3e to your computer and use it in GitHub Desktop.
Save bullishgopher/69e504384fc4e10c45217b4b2fe62f3e to your computer and use it in GitHub Desktop.
80% Cleaner JavaScript Code Using Optional Chaining and Nullish Coalescing
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'

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment