Skip to content

Instantly share code, notes, and snippets.

@sorie
Created August 12, 2021 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorie/9622fc23f6203d6b7cf5baf1161e5681 to your computer and use it in GitHub Desktop.
Save sorie/9622fc23f6203d6b7cf5baf1161e5681 to your computer and use it in GitHub Desktop.
javascript tip : optional chaining
const bob = {
name: 'Julia',
age: 20,
};
const anna = {
name: 'Julia',
age: 20,
job: {
title: 'Software Engineer'
}
};
//bad code
function displayJobTitle(person) {
if(person.job && person.job.title) {
console.log(person.job.title);
}
}
//good code
function displayJobTitle(person) {
if(person.job??.title) {
console.log(person.job.title);
}
}
//good code nullish
function displayJobTile(person) {
const title = person.job?.title ?? 'No Job Yet';
console.log(title);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment